WebMatrix - Working With The JSON Helper

Javascript Object Notation (JSON) is a data exchange format which really grew in popularity as AJAX libraries took off. It's lightweight and human readable, and is a great way of transferring data structures between the browser and the server. The JSON Helper was added in WebMatrix Beta 2, and this article looks at its main methods, and how they can be used.

The 3 main helper methods within Web Pages are Json.Encode(), Json.Decode() and Json.Write(). The first of these takes an object and returns a JSON string. The second has 3 overloads, but the one you are likely to use most often takes a JSON string and returns a dynamically created object. The final one takes an object, serializes it into JSON, and then outputs the result to a TextWriter. Don't worry too much about the TextWriter business just at the moment. We'll look at that soon.

As I mentioned in the introduction, JSON really took off as a result of the growth in popularity of AJAX techniques to communicate with the web server asynchronously. So I'm going to use a jQuery AJAX example which I've nearly done to death to show some of the helper methods at work. The scenario involves a dropdown list featuring customers in the Northwind database. When the user chooses one of the options, an AJAX call is made to the server to retrieve the full address and contact details for the selected customer, and the page is updated to display this. In this case, the details obtained from the database will be Json encoded so that the jQuery code in the page can play with it nicely. A download will be available at the end of the article, which includes a nice Sql CE 4.0 version of Northwind, but if you want to play along in the meantime, you will need to get hold of the latest version of jQuery (currently 1.4.2) and an additional plug-in for managing dropdowns called SelectBoxes.

The page that contains the dropdown list will use a Layout page which references the jQuery files and has an extraordinarily small amount of HTML in it:

<select id="CustomerId" name="CustomerId"></select>
<div id="details"></div>

That's it. There's an html select list, and a div for displaying the selected customer's details. To provide the options for the select list, I've created another cshtml page called ListCustomers.cshtml which will query the database for the customer ID and name, and then return them as JSON. The code could look like this:

@{
    var db = Database.Open("Northwind40");
    var sql = @"SELECT [Customer ID] AS CustomerID, [Company Name] AS CompanyName FROM Customers";
    var data = db.Query(sql);
    var json = Json.Encode(data);
    Response.Write(json);
}

This example shows the Json.Encode() method at work. However, I opted to use the Json.Write() method instead:

@{
    var db = Database.Open("Northwind40");
    var sql = @"SELECT [Customer ID] AS CustomerID, [Company Name] AS CompanyName FROM Customers";
    var data = db.Query(sql);
    Json.Write(data, Response.Output);
}

Do you remember that this method takes an object and a TextWriter as arguments? Well the Output property of the HttpResponse class is a TextWriter object that sends text out from the web server to the requesting client. Functionally, both samples of code above are identical. I just prefer not to use Response.Write unless I have to.

The next step is to add some jQuery to the page with the dropdown list and div on it:

$(function(){
    //Fill the customer drop down
    $('#CustomerId').addOption('',"Loading....").attr('disabled', true);
    $.getJSON('/ListCustomers', function(data) {
        var customers = data;
        $.each(customers, function(index, customer) {
            var val = customer.CustomerID;
            var text = customer.CompanyName;
            $('#CustomerId').addOption(val, text, false);
        });
        $('#CustomerId').removeOption(0).attr('disabled', false);
    });

This makes use of both jQuery and the SelectList plugin. It uses the jQuery getJSON command to request the ListCustomers file, and accepts the JSON which the Json.Write() method sends back into a variable called data. The first line under the comment adds an option to the select list which tells the user that something's happening while the data is fetched in the background. The select list is set to a disabled state while the data is being retrieved and parsed. That option is removed once all the customer data has been populated, and the select list is set back to enabled.

The javascript continues:

    //Post the chosen customer id and retrieve the customer details
    $('#CustomerId').change(function() {
        $.ajax({
        url: "/GetCustomer/" + $(this).val(),
        dataType: "json",
        success: function(data) {
        var customer = data;
        $('#details').empty();
        $('#details').append('<p><strong>' + customer.CompanyName + '</strong><br />' +
                                customer.Address + '<br />' +
                                customer.City + '<br />' +
                                customer.PostalCode + '<br />' +
                                customer.Phone + '<br />' +
                                customer.Fax + '</p>');
        }
      });
    });
  });
  </script>

This section adds an event handler to the onchange event of the select list, so that the selected value is obtained and posted to another file called GetCustomer.cshtml:

@{
    var db = Database.Open("Northwind40");
    var id = UrlData[0] ?? "ALFKI";
    var sql = @"SELECT [Company Name] AS CompanyName, Address, City, [Postal Code] As PostalCode, 
                Country, Phone, Fax FROM Customers WHERE [Customer ID] = @0";
    var item = db.QuerySingle(sql, id);
    Json.Write(item, Response.Output);
}

This file takes the value passed in the AJAX post (a default value is used if there is no posted value) and uses it as a parameter value in the WHERE clause to get the right record. Again, Json.Write() is used to send the json string back to the browser containing the customer's address details. That is passed to the variable data in the second half of the jQuery, which is responsible for displaying it in the details div.

Lastly, a brief look at the Json.Decode() method. This does exactly what it suggests, but decoding JSON and returning a dynamic object:

@{
    var customer = Json.Decode("{\"CompanyName\":\"Centro comercial Moctezuma\"," + 
        "\"Address\":\"Sierras de Granada 9993\",\"City\":\"México D.F.\"," + 
        "\"PostalCode\":\"05022\",\"Country\":\"Mexico\",\"Phone\":\"(5) 555-3392\"," + 
        "\"Fax\":\"(5) 555-7293\"}");
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
    <p>
        <strong>@customer.CompanyName</strong><br />
                @customer.Address<br />
                @customer.City<br />
                @customer.PostalCode<br />
                @customer.Phone<br />
                @customer.Fax
        </p>
    </body>
</html>

The preceding code sample illustrates this by taking a piece of JSON representing the output from the GetCustomer.cshtml file and parses it into a dynamically created C# object called customer. Each of the properties of that object is then written to the browser using Razor syntax.

Download the sample code from GitHub.

Date Posted: Friday, October 15, 2010 6:51 PM
Last Updated: Thursday, August 29, 2013 10:28 AM
Posted by: Mikesdotnetting
Total Views to date: 27751

13 Comments

Friday, October 15, 2010 11:09 PM - camus

great as usual.

Wednesday, October 20, 2010 4:45 AM - Mike

Great article Mike. Really appreciate you taking the time to help familiarize us with WebMatrix and its various helpers. Please keep up the good work.

Cheers
Mike

Sunday, October 31, 2010 5:05 AM - nick Hrones

Thanks!
Very well writen and very informative. Your tutorials are helping me significantly. you should publish a 'WebMatrix for beginners' book! I'd buy it!
Thanks again,
Nick

Sunday, October 31, 2010 6:50 AM - Mike

@Nick

Glad you like the articles.

And watch this space....

;o)

Tuesday, March 8, 2011 9:01 PM - Mark R Evans

Thanks so much for the terrific articles on Webmatrix. I'm currently using this to create a prototype for a new application I want to demo. I am using APIs that return JSONs and thought it would be helpful to convert the JSONs into Webgrids. Looking at the articles you've posted, I don't see a straightforward way to do this?

Thanks!

Mark

Tuesday, March 8, 2011 10:03 PM - Mike

@Mark,

I would use the Json.Decode<T> method to convert the JSON to a strongly typed list and pass that into the source parameter of the WebGrid.

Friday, May 6, 2011 9:08 AM - vinay

nice article

Thursday, July 12, 2012 12:28 PM - Charles Wong

it's that “$('#CustomerId').addOption” a custom method?

Saturday, July 14, 2012 9:23 PM - Mike

@Charles

It belongs to the SelectBoxes plugin that I mentioned and linked to in the body of the article.

Tuesday, January 8, 2013 12:34 PM - 23234

great

Tuesday, August 13, 2013 9:56 AM - Abhishek Luv

Great post Mike sir!

Thursday, August 15, 2013 4:39 PM - Michael

Great example! Any reason you have a for loop inside the each loop in the first callback function on default page? I used to develop in plain ASP 10 years ago, but I'm new to JQuery, JSON, and Razor so this stuff is kinda new to me. I'm just wondering if I'm missing something, but the page seems to work fine if I comment out the for loop and just leave the each loop. Thanks!

Thursday, August 29, 2013 10:13 AM - Mike

@Michael,

No - the for loop is completely unnecessary. I have removed it. Thanks for spotting that.
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.