Click here to Skip to main content
12,894,700 members (54,432 online)
Click here to Skip to main content
Articles » Web Development » ASP.NET » Howto » Downloads


67 bookmarked
Posted 27 Oct 2009

Saving ASP.NET Form Data with jQuery AJAX and JSON Parser

, 27 Oct 2009 CPOL
Using jQuery AJAX and the JSON.Net parser to process ASP.NET webform data and avoid page post back.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<!--                           INTRODUCTION                                

 The Code Project article submission template (HTML version)

Using this template will help us post your article sooner. To use, just 
follow the 3 easy steps below:
     1. Fill in the article description details
     2. Add links to your images and downloads
     3. Include the main article text

That's all there is to it! All formatting will be done by our submission
scripts and style sheets. 

<!--                        IGNORE THIS SECTION                            -->
<title>Saving ASP.Net Form Data with jQuery AJAX and JSON Parser</title>
BODY, P, TD { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt }
H2,H3,H4,H5 { color: #ff9900; font-weight: bold; }
H2 { font-size: 13pt; }
H3 { font-size: 12pt; }
H4 { font-size: 10pt; color: black; }
PRE { BACKGROUND-COLOR: #FBEDBB; FONT-FAMILY: "Courier New", Courier, mono; WHITE-SPACE: pre; }
CODE { COLOR: #990000; FONT-FAMILY: "Courier New", Courier, mono; }
<link rel="stylesheet" type="text/css" href="">
<body bgcolor="#FFFFFF" color=#000000>

<!-------------------------------     STEP 1      --------------------------->
<!--  Fill in the details (CodeProject will reformat this section for you) -->

Title:       Saving ASP.Net Form Data with jQuery AJAX and JSON Parser
Author:      Steve S. Yang 
Member ID:
Language:    C# 3.0
Platform:    Windows, .NET 3.5
Technology:  ASP.NET 2.0, 3.5
Level:       Intermediate
Description: Using jQuery Ajax and JSON.Net parser to process ASP.Net webform data and avoid page post back
License:     <a href="">CPOL</a>

<!-------------------------------     STEP 2      --------------------------->
<!--  Include download and sample image information.                       --> 

<ul class=download>
<li><a href="">Download source code - 314 Kb </a></li>


<!-------------------------------     STEP 3      --------------------------->

<!--  Add the article text. Please use simple formatting (<h2>, <p> etc)   --> 


<p>I came forth to write this down because of my own frustration of having hard time to find good sample codes to get me to where I wanted.  
Basically, I wanted my page where I had a form for entering expense item to do the following:
<li>When I clicked on a Save button on the form, I did not want post back as the post back would mess up with something on the form, not just do it for the sake of no post back. To implement that, I chose to use Jquery Ajax Post to send form data wrapped in a 
    JSON format to another page for processing. Yes, I could have simply used an Update Panel from ASP.NET Ajax controls kid, but that was not what I wanted in this case.</li> 
<li>The Ajax processing page would retrieve the JSON data object and do the database update.</li>
<li>Once database update was done, the page would send a response text back to where the Ajax call was initiated and update the front page.</li>
My objective was quite simple but it took me more time than what I thought would need to accomplish it.  
And the reason was simply because this time around, I was unable to find enough references to guide me through, so I had to spend a lot of time developing solution via trial-and-error method. Therefore once I came up with solution, I told myself I needed to share this with others as I benefited a lot in the past from the community by looking at other programmers' postings.


<h2>Access form element via jQuery wildcard selector</h2>
    The first challenge I encountered was to retrieve all form elements that were server bounded � either web control 
by itself or web control inside a user control. The ClientID of web control could be used but I did not like to mix 
too many server tag <code>&lt;&#37=var&#37&gt;</code> with Javascript plus they might impede Javascript performance. 
Thankfully, jQuery wildcard selector has made this easy and clean.<br />

        Here is an example how this is done:<br />
        <pre>var <code>recordid</code> = $(�[id$=�txtRecordID�]�).val();
        <br />
This will get me the text value in a server-side textbox control 
&lt;asp:TextBox ID="txtRecordID" runat="server" Width="100px"&gt;&lt;/asp:TextBox&gt;
But what about a TextBox in a Web User Control? That was what I used wildcard for � to get to the element that has 
a client id ended with a server control id.  Normally if I simply place a TextBox control on a web form, 
the client id will be exactly same as the ID I use in server side; in that case, <pre>$(�#txtRecordID�)</pre>
 will return the same element object as <pre>$(�[id$=�txtRecordID�]�).</pre> 
 But most of times, we group certain web controls on a User Control then use the UserControl on a web form. 
 In that case, <code>$(�#txtRecordID�)</code> will get you nothing because now you have a user control id 
 added to the client id for the TextBox, so now you will use <b>wildcard selector</b> instead: <code>$(�[id$=�txtRecordID�]�)</code>.  
 To assure that the wildcard will return the unique element, you can add the User Control server id to make it look like this: <pre>$(�[id$=�ucMyControl_txtRecordID�]�).</pre>
   (In some cases, you might have two or more server controls that are all named txtRecordID sitting in separate user controls that are embedded in same web form, then it is absolutely necessary that you add the user control id into the jQuery wildcard search. 
   I picked up this syntax for searching element ending with a specific server id from web community somewhere sometimes ago but I was unable to locate the source again to give a reference Url here. 
   But I did come across a similar post as of this writing at <a href="" target="_blank"></a> 
   that was using wildcard for searching element beginning with a specific id, and the syntax looks like this <code>$(�[id^=pnl]).hide() </code>   - hide all the divs that start with a �pnl� in their control ids.       

<h2>Send JSON-formatted data via jQuery Ajax</h2>
Now that I cleared the way to gain access to server side element via jQuery wildcard selector, 
I collected the data and stringed them into a <a href="" target="_blank">JSON format</a>.  
JSON is just another lightweight alternative of XML format and here is my simlified version JSON data string:

	<pre id="#myEscape">var <code>json</code>=�{�RecordID�:�� + $(�[id$=�txtRecordID�]�).val() + ��,�ItemName�:�� <br />
    + escape($(�[id$=�txtItemName�]�).val()) + ��,�CategoryID�:�� + (�[id$=�ddlCategories�]�).val() + ��}�;</pre>
I packed my form data into a JSON formatted string simply because I wanted to use <a href="" target="_blank">JSON.Net API tool</a> to parse it 
later on the other end of the wire. Nothing was for the fancy of using JSON.  I used �escape� function in front of all text fields to encode any possible odd character such as an apostrophe that can throw JSON parser off.  
<br /><br />

Next, I sent the data via jQuery Ajax, using the syntax as below:
<br />
var <code>to</code>=�DataProcessor.aspx?Save=1�;
var <code>options</code> = {
            type: "POST",
            url: <code>to</code>,
            data: <code>json</code>,
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: false,
            success: function(response) {
                //alert("success: " + response);
            error: function(msg) { alert(msg); }

        var <code>returnText</code> = $.ajax(<code>options</code>).responseText;

Here <code>response</code> in the success section is same as the <code>responseText</code> returned from <code>$.ajax</code>.

<h2>Retrieve JSON data from Request.InputStream</h2>
Then, I went into the <code>DataProcessor.aspx</code> code behind and did the following steps to retrieve and parse the data:

<li>Check the Content type of the Request object  using this syntax: 
<pre>if (Request.ContentType.Contains("json") && Request.QueryString["Save"]!=null)<br />
<li>The function <code>SaveMyData</code> retrieved the JSON data by reading <code>InputStream</code> from <code>Request</code> object, as shown below:<br />
System.IO.StreamReader sr = new  System.IO.StreamReader(Request.InputStream);<br />
        	string line = "";<br />
        	line = sr.ReadToEnd();<br />
At this point, the string variable <code>line</code> contain a JSON formatted string like : 
I could have created my own function to parse out this string and be done with it. But why should I re-invent the wheel, 
while there is already something called JSON.NET out there? Surely, I found the needed API from 
<a href="" target="_blank"></a> and downloaded the library 
for .Net 3.5 version. Following the instruction that came with the download, I added the assmebly <code>Newtonsoft.Json.dll</code>
 to my project and imported the namespace <code>Newtonsoft.Json.Linq</code> to the page class; then there it was � just one line of code to do the parsing:
     	JObject jo = JObject.Parse(line);

Once my JSON-formatted string variable,<code>line</code>, was parsed, I accessed each property through following codes:

Remember I did an <a href="#myEscape">escape</a> for <code>ItemName</code> when I packed the form data into a JSON string in <code>DataForm.aspx</code>? Here I did an equivalent of �unescape� using Server.UrlDecode so the �%20� will return to space and �%27s� to ��s�, and so on.
You don�t want to UrlDecode before running the data downloaded from Request.InputStream through JObject parser as some JSON unfriendly characters like an apostrophe (���) will blow the parser. So only do UrlDecode after JObject.Parse() and do it to each individual property of string type.

Once the data is parsed, I processed them to data tier and return a record id back to front page simply by calling Response.Write(). To simplify the demo, I did not include any database logic here; instead, I simply used the �CategoryID� passed in to simulate if the database update is successful or failed: 

           <pre> 	Response.Write((string)jo["CategoryID"]); </pre>

This is what got to the <code>jQuery.ajax(options).responseText</code>.  You can also pack a long Html string and shuffle it back to <code>.ajax().responsText</code> to render on the front page.
<br />		 
Now I returned to the front page and retrieved the responseText as follow:  
var returnText = $.ajax(options).responseText;
        if (returnText > 0) {
        $("[id$='txtRecordID']").html( returnText);
        $("#divMsg").html("&lt;font color=blue&gt;Record saved successfully.&lt;/font&gt;");         
        //$("#divMsg").addClass("SuccessMsg"); //if you prefer to use class
        else {

            $("#divMsg").html("&lt;font color=red&gt;Record was not saved successfully.&lt;/font&gt;");         
            //$("#divMsg").addClass("ErrorMsg"); //if you prefer to use class


Put them together, here were how things moved: used jQuery wildcard selector 
<code>$(�[id$=�serversidecontrolid�]�)</code> to retrieve form data that were stored in the server controls such as TextBox, 
and DropDownList, constructed them into a JSON string, then used <code>jQuery.Ajax()</code>
 to POST JSON data to a different ASP.Net page for processing; 
 downloaded the JSON data from other side using a <code>System.IO.StreamReader</code> to read off the 
 <code>Request.InputStream</code> object, 
 then used JSON parser API provided from JSON.Net to parse the JSON data string into JObject. 
 Once data was saved, used Response.Write to return the result to front page.<br /><br />
 I was satisfied with this light weight solution that helped me get rid of the heavy 
foot-printed ASP.NET AJAX Update Panel to overcome page post back.  
My goal of writing this paper, also my first ever article for CodeProject, was to share my research and connect pieces so others will not have to repeat the 
frustration I experienced when I first started it and could only found a piece here and a piece there.  



By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.


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


About the Author

Steve S. Yang
Web Developer Bisk Education, Inc
United States United States
No Biography provided

You may also be interested in...

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170424.1 | Last Updated 27 Oct 2009
Article Copyright 2009 by Steve S. Yang
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid