Nov 14 2006

Update multiple AJAH controls using JSON

Posted by admin under Ajax

In this article we updated two controls from a single Ajax callbut to be honest the code was not all that beautiful. We genarated html on the serverside for each of controls and separated them by using a special sequence of characters, '##########' - which was then splitted clientside by using javascript.

I really wanted to show you that technique, cause while it might not be the coolest or most correct it might be good enough fir you - and if so, great - just use it!

However, personally I have gotten into JSON a lot lately and the cool thing about it is (besides from being really lightweight as compared to XML) that it will allow for object oriented access from our JavaScript.

The goal with this article is to be able to write our client side Javascript code like this (in our Ajax callback handler):



function AjaxGetHTML(sUrl)
{
    $.get(sUrl,function(result)
        {
            var oResultData = eval('(' + result + ')');
            var oItem;
            for(var n = 0; n < oResultData.controls.length; n++)
            {
                oItem = oResultData.controls[n];
                if ( oItem.name == 'employees' )
                    $('#repeater1').html( oItem.data );
                if ( oItem.name == 'terr' )
                    $('#repeater2').html( oItem.data );
            }
        
        });
 }



Looking cool doesn't it? The result from our Ajax call gets translated to an object by using eval function - and then that object contains a controls collection. We loop through that collection and each item contains a name property and a data property (containing the html).

Lets look at the serverside code for that:



protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Request["w"] != null && Request["w"] == "callback")
        {
            rptTable.DataSource = GetData(Request["filter"]);
            rptTable2.DataSource = GetData2(Request["filter"]);
        }
        else
        {
            rptTable.DataSource = GetData("");
            rptTable2.DataSource = GetData2(Request["filter"]);
        }
            
        rptTable.DataBind();
        rptTable2.DataBind();
        if (Request["w"] != null && Request["w"] == "callback")
        {
            ///Create a JSON string
            ///
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            System.Text.StringBuilder oBuilder = new System.Text.StringBuilder();
            oBuilder.Append("{");
            oBuilder.Append(" \"controls\" : [");
            oBuilder.Append("{");
            oBuilder.AppendFormat(" \"name\" : \"employees\", \"data\": {0}  ", 
                    Enquote(GetHtml(rptTable)));
            oBuilder.Append("},");
            oBuilder.Append("{");
            oBuilder.AppendFormat(" \"name\" : \"terr\", \"data\": {0}  ",
                Enquote(GetHtml(rptTable2)));
            oBuilder.Append("}");

            oBuilder.Append(" ] }");


            Response.Write(oBuilder.ToString());
            Response.End();

        }
    }
}


It's simply a matter of creating our JSON string (not descrobed in details here) - however when I first ran it I got a lot of unrecognized character sequences errors in the client code.

And the HTML of course contains a lot of special characters etc - what we need to do is encode it - allowed characters are defined at the JSON.org home page . Anyway I was able to find a function for encoding it - called Enquote - so that's doing some magic on our HTML code before it's put into the resulting JSON string.

 

Attachments