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!
- First add a page in required directory in the ASP.NET Web Application. Please see DataProvider.aspx in the attached solution.
- Remove all tags except the
page
tag from HTML Markup of the page
- 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
- Serialize the data either by
JavaScriptSerializer
or XmlSerializer
and get the serialized string
- Write the serialized data string using
Response.Write(jsonDataString);
- 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