Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
27 Feb 2015 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here