Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
4.72/5 (22 votes)
27 Oct 2009CPOL7 min read 172.5K   7.2K   67  
Using jQuery AJAX and the JSON.Net parser to process ASP.NET webform data and avoid page post back.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Newtonsoft.Json.Linq;   //downloaded JSON.net from http://james.networking.com/projects/json-net.aspx


namespace CodeProjects
{
    public partial class DataProcessor : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                ProcessAjaxRequest();



        }




        private void ProcessAjaxRequest()
        {
            if (Request.ContentType.Contains("json") && Request.QueryString["Save"] != null)
                SaveMyData();




        }


        private void SaveMyData()
        {
           
            //data passed in as JSON format
            System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
            string line = "";
            //while (!sr.EndOfStream)
            //{

            //    line = sr.ReadLine();        //do not do Server.UrlDecode here as it might render those escaped characters that will blow up JObject parsing
            //    Console.WriteLine(line);


            //}

            line = sr.ReadToEnd();

            
            //This is all you need to parse JSON string into an JObject. 
            //Require namespace Newtonsoft.Json.Linq;
            JObject jo = JObject.Parse(line);
            
            Console.WriteLine((string)jo["RecordID"]);
            Console.WriteLine(Server.UrlDecode((string)jo["ItemName"])); //use Server.UrlDecode to reverse the text that was escaped before it was passed in to its original state

            //do data saving logic here and return the recordid
            //int recordid=SaveToDataBase(jo);
            //Response.Write(recordid.ToString());

            Response.Write((string)jo["CategoryID"]); //this send to responseText of .ajax(options).responseText




        }


    }
}

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.

License

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


Written By
Web Developer Bisk Education, Inc
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