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

13 Comments

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

Cheers
Mike

- 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

- Mike

@Nick

Glad you like the articles.

And watch this space....

;o)

- 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

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

- vinay

nice article

- Charles Wong

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

- Mike

@Charles

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

- 23234

great

- 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

@Michael,

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

Recent Comments

sandeep 8/28/2015 7:03 AM
In response to 7 C# 6.0 Features That Every ASP.NET Developer Should Know About
very good article, i like it........keep writing such quality article in future. thx Mike....

Hassan, MVC Learner 8/28/2015 6:37 AM
In response to Get The Drop On ASP.NET MVC DropDownLists
Great Help, simple, great and patiently explained article !...

Anvesh 8/28/2015 12:39 AM
In response to ASP.NET MVC DropDownLists - Multiple Selection and Enum Support
what if we are taking postback values from FormCollections instead of an array int[] category. How...

Ben 8/27/2015 10:50 PM
In response to Simple File Download Protection with ASP.NET
Is it possible to setup your project to publish files to outside of your root directory? I would to...

Fred 8/26/2015 12:50 AM
In response to WebMatrix Opens Wrong Version Of Visual Studio
I enjoyed many of your tutorials but the problem is none of the tutorials are combined like most be....

Muhammad Ashikuzzaman 8/25/2015 2:48 PM
In response to Managing Checkboxes And Radios In ASP.NET Razor Web Pages
That's a very good tips for razor...

Sergey 8/25/2015 8:32 AM
In response to More Flexible Routing For ASP.NET Web Pages
Hi. How I can set up my site to get urldata from link for default page? site.com/default/1-...

Tony Gray 8/25/2015 6:27 AM
In response to Adding Validation
Hi Mike, Really helpful article and series. Thanks. Small typo in 4th paragraph you have so...

amanda n 8/25/2015 12:38 AM
In response to Solving the Operation Must Use An Updateable Query error
Thank you very much. I'm a uni student and while solving coding problems is usually enjoyable and me...

salman 8/23/2015 9:25 AM
In response to How To Send Email In ASP.NET MVC
thanks ......