Sending data from codebehind to javascript

Monday, September 05, 2011

4

*Feb 2015 Edit: For a solution to the slightly more complex problem of asynchronously calling server-side code from Javascript, and sending back the results, check out my ICallbackEventHandler post.


A few days ago I had to implement a page that lets users apply filters to a dataset (from SharePoint) without reloading the page.  My initial thought was to either:

  1. Use an ajax UpdatePanel.  This would require a postback, but the user wouldn't notice it.
  2. Use jQuery to make a webservice call to the SharePoint search service, and update the page with the results.  This would happen completely on the client side.

    Unfortunately, for this particular project both ajax and the search service were off limits.  Also, the dataset was tiny (< 50 rows) so posting back or re-querying seemed like a waste.  Some research led to a very elegant third option:

    1. Get the entire dataset before the page renders (in codebehind)
    2. Serialize the dataset to JSON format
    3. Render the JSON dataset onto the page as a javascript variable so that it can be manipulated clientside

    Now the JSON data can filtered completely on the client side using jQuery or plain javascript.  This option doesn't require postbacks or hitting a webservice, and the JSON data can be manipulated in object oriented fashion.

    Here's an example with two simple datamodel classes, Company and Employee:


    Say we have a method GetAllCompanies() that returns an array of Companies, which we want to manipulate client side.  First we have to serialize the array into JSON.  Luckily, there there's a JavaScriptSerializer under the System.Web.Script.Serialization namespace that does exactly that.  Next we render the JSON string onto the page as a javascript variable:


    If you look at the page source after the page loads, there should be a script block with the JSON data that looks like something like this:

    Now the object oriented data in the 'companies' variable can be manipulated from javascript!


    Javascript blocks are processed top to bottom, so make sure the JSON script block appears above any script that uses that data.  Otherwise, the variable will be undefined.


    4 comments:

    This is a brilliant technique

    Hi. Could you please provide the sample code used in the function GetAllCompanies()

    That depends on where you're getting the companies from. If you are pulling from a SharePoint list, you'd go through and map whichever fields you're interested in from the SPListItems to Company objects. For example:

    List< Company > companies = new List< Company >();

    using (SPWeb web = new SPSite("http://Server").OpenWeb())
    {
    SPList list = web.Lists["Companies"];

    for (int i = 0; i < list.ItemCount; i++)
    {
    Company c = new Company();
    c.Name = list.Items[i].Name;

    companies.Add(c);
    }
    }

    return companies.ToArray();

    Post a Comment