Basic Simple Asp.net + jQuery + JSON example

There are several ways that you can do this; this will serve as a single example.

You could write something like this for your jQuery code:

urlToHandler="handler.ashx";
jsonData="{ "dateStamp":"2010/01/01", "stringParam": "hello" }";
$.ajax({
                url: urlToHandler,
                data: jsonData,
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json',
                success: function(data) {                        
                    setAutocompleteData(data.responseDateTime);
                },
                error: function(data, status, jqXHR) {                        
                    alert('There was an error.');
                }
            }); // end $.ajax

Next, you need to create a “generic handler” in your ASP.net project. In your generic handler, use Request.Form to read the values passed in as json. The code for your generic handler could look something like this:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class handler : IHttpHandler , System.Web.SessionState.IReadOnlySessionState
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";

        DateTime dateStamp = DateTime.Parse((string)Request.Form["dateStamp"]);
        string stringParam = (string)Request.Form["stringParam"];

        // Your logic here

        string json = "{ \"responseDateTime\": \"hello hello there!\" }";
        context.Response.Write(json);    
    }

See how this work out. It will get you started!

Update: I posted this code at the CodeReview StackExchange: https://codereview.stackexchange.com/questions/3208/basic-simple-asp-net-jquery-json-example

Leave a Comment