Oct 27 2006

JQuery and ASP.NET - returning classes with JSON

Posted by admin under Ajax

This article is part of an article serie - please start by reading ASP.NET and JQuery - first example , JQuery and ASP.NET - lets involve ASP.NET  and Ajax loading animation with JQuery and ASP.NET  and Timed Ajax calls with JQuery and ASP.NET .

Now we are gonna do port of the Ajax.NET solution of the case presented in this article Ajax.NET returning classes  .

 

In other words - we have multiple fields we want to update though just a single Ajax call:

Periodically (every 10 seconds) we make an Ajax call to our handler with ajaxdata.ashx?what=resuldata - and there we create an instance of the ResultData class:



    public void ProcessRequest (HttpContext context) {
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
        context.Response.ContentType = "text/plain";
        
        if ( context.Request["what"] != null && context.Request["what"] == "resuldata" )
            context.Response.Write(new ResultData().GetResultDataJSON());
        else
            context.Response.Write(TimeServer.Minute());
    }



Now lets look at the ResultData class - as you can see we call a function GetResultDataJSON() which appearantly generates the response to send to the client browser :



public class ResultData
{

    public int Minute;
    public string Guid;
    public DateTime Updated;

    public ResultData()
    {
        Minute = DateTime.Now.Minute;
        Guid = System.Guid.NewGuid().ToString();
        Updated = DateTime.Now;
    }

	public string GetResultDataJSON()
	{
        StringBuilder oBuilder = new StringBuilder();        
        oBuilder.Append("{");
        oBuilder.AppendFormat("'{0}' : {1},", "Minute", Minute.ToString());
        oBuilder.AppendFormat("'{0}' : '{1}',", "Guid", Guid);

        //Datetime special - javascript date is ms after 1 jan 1970
        TimeSpan oSpan = Updated - new DateTime(1970,1,1,0,0,0);

        oBuilder.AppendFormat("'{0}' : new Date({1})", "Updated", oSpan.TotalMilliseconds.ToString("0"));
        oBuilder.Append("}");
        return oBuilder.ToString();
	}


}



 

Not much to say about the variables - however what we are trying to achieve is for our client (JavaScript code) to be able to work with the result in an object oriented way:



            $('#divguid').html( oResultData.Guid );
            $('#lblDataUpdated').html( oResultData.Updated.toGMTString()  );
            if ( parseInt( $('#lblMinute').text() ) != parseInt(oResultData.Minute) )
            {
                $('#lblMinute').html(oResultData.Minute);






Doesn't that look cool - in Javascript it looks like we are working against a ResultData object - accessing the properties Guid, Updated, Minute etc.

The secret is JSON. On the serverside we serialize the result in a specific format called JSON - which will allow us (in our client javascript code) to in a single call create an object with properties.

First lets look again at the GetResultDataJSON function:



	public string GetResultDataJSON()
	{
        StringBuilder oBuilder = new StringBuilder();        
        oBuilder.Append("{");
        oBuilder.AppendFormat("'{0}' : {1},", "Minute", Minute.ToString());
        oBuilder.AppendFormat("'{0}' : '{1}',", "Guid", Guid);

        //Datetime special - javascript date is ms after 1 jan 1970
        TimeSpan oSpan = Updated - new DateTime(1970,1,1,0,0,0);

        oBuilder.AppendFormat("'{0}' : new Date({1})", "Updated", oSpan.TotalMilliseconds.ToString("0"));
        oBuilder.Append("}");
        return oBuilder.ToString();
	}


}



If you forget about the datetime stuff - in short we are creating a string looking like this:

{
 'Minute' : 15,
 Guid : 'd33a7e48-a076-41b5-b927-3b5f4820e11b',
 'Updated' : new Date(1231321...)
}

And that's exactly the format Javascript could use to create an object with properties Minute, Guid and Updated. We create such an object by using the javascript eval function on the string:



function MyUpdate()
{
    $.get("ajaxdata.ashx?what=resuldata",function(result)
        {
            var oResultData = eval('(' + result + ')');
            $('#divguid').html( oResultData.Guid );
            $('#lblDataUpdated').html( oResultData.Updated.toGMTString()  );
            if ( parseInt( $('#lblMinute').text() ) != parseInt(oResultData.Minute) )
            {
                $('#lblMinute').html(oResultData.Minute);
                $('#lblMinute').fadeOut(450);
                $('#lblMinute').fadeIn(450);
                $('#lblMinute').fadeOut(450);
                $('#lblMinute').fadeIn(450);
                $('#lblMinute').fadeOut(450);
                $('#lblMinute').fadeIn(450);
            }
        });
    setTimeout(MyUpdate,10 * 1000);
 }

Now, please download the attached VS2005 solution and have a look yourself - personally I must say I am getting more and more impressed over Javascript as a programming language.

 UPDATE: According to JSON spec it seems like ' should not be used but ".

Therefore change the code in GetResultDataJSON() like this:

        oBuilder.AppendFormat("\"{0}\" : {1},", "Minute", Minute.ToString());
        oBuilder.AppendFormat("\"{0}\" : \"{1}\",", "Guid", Guid);
...

        oBuilder.AppendFormat("\"{0}\" : new Date({1})", "Updated", oSpan.TotalMilliseconds.ToString("0"));