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: 32276

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

Gayan 7/3/2015 6:20 AM
In response to 7 C# 6.0 Features That Every ASP.NET Developer Should Know About
Great Article thanks...

Semil 7/1/2015 7:03 AM
In response to iTextSharp - Drawing shapes and Graphics
I have created a rectangle using above methode. Now I want to add a text in the center of this How I...

Satyabrata Mohapatra 6/30/2015 6:12 PM
In response to Reading Excel Files Without Saving To Disk In ASP.NET
Ahh.....this is awesome. Happy to see after a long time you wrote a article on web form :D...

Marty 6/30/2015 7:16 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Mike, you're the Man! Another great article. So incredibly helpful. I'm definitely going to buy your...

Rohan 6/30/2015 5:32 AM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Very good and helpful tutorial. Thanks. Just wanted to know what would be the max file size limit we...

Fernando 6/30/2015 1:59 AM
In response to Programmatically accessing data from DataSource controls
What if I want to pass parameters natively using the DataSourceSelectArguments object, instead of be...

pankaj 6/29/2015 3:13 PM
In response to How to retain carriage returns or line breaks in an ASP.NET web page
very nice i'm use this in my code thank you.... ...

Mike 6/29/2015 2:22 AM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
This is the first example that I have found that works....

Marty 6/28/2015 4:57 AM
In response to Posting Data With jQuery AJAX In ASP.NET Razor Web Pages
Mike, what if I don't want to render back the text to the browser, but I want to send it some other...

Mike 6/27/2015 4:00 PM
In response to Migrating Classic ASP To ASP.NET Razor Web Pages Part One- Razor Syntax And Visual Basic
have you used any of the code converters to convert classic asp to c#? If so, which one do you have...