Click here to Skip to main content
15,890,845 members
Articles / Web Development / HTML
Tip/Trick

How to Use ASP.NET WebForm for JSON or XML Response

Rate me:
Please Sign up or sign in to vote.
4.60/5 (3 votes)
27 Feb 2015CPOL2 min read 25.8K   1.2K   5  
Shows how to use simple ASPX page to return JSON or XML response

Introduction

There are times when we need to pull the data out of database and use it for displaying/populating dropdown(s), custom tooltip(s), table(s) etc. Instead of creating ASMX/WCF Service with web.config file for endpoint configuration, we can use ASP.NET WebForm (.aspx) file to return the required (XML or JSON) responses.

Background

The code in the solution shows how you can use the ASPX page to pull the data and return the data as JSON or XML format back to the caller function.

The code in the solution I am already using in one of the projects for displaying the child records of the selected (i.e., on which user will mouse over) parent record. When user hovers mouse pointer on the link, it requests the data by calling *.aspx.

Please have a look at the attached solution for the details. The code in the solution uses ASPX, jQuery, HTML and C#.

Using the Code

The solution is simple and here is how, just follow these simple steps and you are done!

  1. First add a page in required directory in the ASP.NET Web Application. Please see DataProvider.aspx in the attached solution.
  2. Remove all tags except the page tag from HTML Markup of the page
  3. In the code behind of the page inside page_load event, set the ContentType of the Response as desired (either JSON or XML) Response.ContentType = "application/json"; //JSON Text output
  4. Serialize the data either by JavaScriptSerializer or XmlSerializer and get the serialized string
  5. Write the serialized data string using Response.Write(jsonDataString);
  6. Consume the newly created ASPX wherever required from within AJAX call. [Note: Only for this step, I used the tooltip example provided by mkyong I’ve provided the link below.

[Note: In the following demo, I used the some or all code technique available at this link. Thanks to mkyong for providing a nice example of creating tooltip.]

Points of Interest

I wanted to create something simple without postback, without using WCF service and just to avoid extra configuration. I used this solution around 10-11 years back. Back then, I used similar aspx page to retrieve the XML data for Adobe Flex Builder 2.0 Chart solution which I built to generate Charts.

History

  • 27th February, 2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --