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);

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:

    //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() {
        url: "/GetCustomer/" + $(this).val(),
        dataType: "json",
        success: function(data) {
        var customer = data;
        $('#details').append('<p><strong>' + customer.CompanyName + '</strong><br />' +
                                customer.Address + '<br />' +
                                customer.City + '<br />' +
                                customer.PostalCode + '<br />' +
                                customer.Phone + '<br />' +
                                customer.Fax + '</p>');

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">
        <meta charset="utf-8" />
        <strong>@customer.CompanyName</strong><br />
                @customer.Address<br />
                @customer.City<br />
                @customer.PostalCode<br />
                @customer.Phone<br />

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:
Last Updated:
Posted by:
Total Views to date: 30831


- camus

great as usual.

- 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.


- nick Hrones

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,

- Mike


Glad you like the articles.

And watch this space....


- 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?



- Mike


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.

- vinay

nice article

- Charles Wong

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

- Mike


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

- 23234


- Abhishek Luv

Great post Mike sir!

- 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!

- Mike


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 I end up deleting quite a lot. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Requests to fix your code (post a question to forums.asp.net instead, please)
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam

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

Recent Comments

Senad Mustafa 3/31/2015 8:57 AM
In response to ASP.NET MVC DropDownLists - Multiple Selection and Enum Support
Hi Mike, Thanks for the articles on dropdownlists. They are really great but I think you are one...

Black 3/28/2015 4:02 AM
In response to Displaying One-To-Many Relationships with Nested Repeaters
it's working. thank for the code...

Lorenzo 3/26/2015 8:21 AM
In response to iTextSharp - Introducing Tables
Hi Mike How can I add padding to all cells in the table? Kind Regards Lorenzo...

Satyabrata Mohapatra 3/25/2015 8:11 AM
In response to How To Send Email In ASP.NET MVC
Great article. Simple and up to the point....

Afzaal Ahmad Zeeshan 3/24/2015 8:17 PM
In response to How To Send Email In ASP.NET MVC
A great way to teach the MVC framework for sending the emails... Also, what I found helpful was the...

Jim H 3/24/2015 2:32 PM
In response to Migrating From Razor Web Pages To ASP.NET MVC 5 - Model Binding And Forms
Thank you. This helps....

wazz 3/22/2015 5:48 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
great info!!...

rael 3/21/2015 8:53 PM
In response to Getting the identity of the most recently added record
I spent hours trying to figure how to achieve this in C#. This article helped me. Thanks a lot...

Stephen 3/21/2015 8:48 PM
In response to Ajax with Classic ASP using jQuery
This was very helpful, thanks:)...

patrick voes 3/19/2015 10:19 AM
In response to iTextSharp - Introducing Tables
Thank you! very helpfull....