WebMatrix - Working With The JSON Helper

4.81 (31 votes)

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

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

- Micheal

Your tutorials are exceptional, sir! Even a beginner like myself can begin to learn how all of this can fit together. I do have a question though. I took some of your code and pulled some data from a database. I was also able to encode it and output it to webpage so that I can query the site for specific data. However, I am stuck with the microsoft date format apparently. Do you know how to change that? (I am using webmatrix and .net framework 4.0)


@{
var db1 = Database.Open("LGOnline");
var formValue2 = Request.Form["STORE_NO"];
var formValue3 = Request.Form["DATE"];
if (IsPost)
{
Response.Redirect("JSON - CashOS.cshtml?&STORE_NO=" + formValue2 + "&DATE=" + formValue3);
}
var Keyword2 = Request.QueryString["STORE_NO"]; //Retrieves passed variable from the database search page for STORE_NO
var Keyword3 = Request.QueryString["DATE"]; //Retrieves passed variable from the database search page for DATE

var sqlQ = "SELECT * FROM CashOS WHERE STORE_NO LIKE @0 AND DATE LIKE @1";
var dataQ = db1.Query(sqlQ, "%" + Keyword2 + "%", "%" + Keyword3 + "%");
var requestedData = dataQ.Select(x => new
{
ID = x.ID,
STORE_NO = x.STORE_NO,
DATE = x.DATE,
MWS_AMOUNT = x.MWS_AMOUNT,
FINAL_AMOUNT = x.FINAL_AMOUNT
}).ToArray();

var json = Json.Encode(dataQ);
Response.Write(json);
Response.ContentType = "application/json";
}

- Micheal

I also meant to post here that my output is this:
[{"ID":1,"STORE_NO":3,"DATE":"\/Date(1442811600000)\/","MWS_AMOUNT":9.5400,"FINAL_AMOUNT":12.3300}

Recent Comments

Jon 31/03/2016 21:36
In response to Exploring Prefix: A Free ASP.NET Profiling Tool
We had the exact same experience, finding multiple bugs in an application that we thought was pretty...

ranjith 31/03/2016 05:50
In response to A Better Way To Export Gridviews To Excel
Hello Mike. i am exporting from gridview, because i have some images in my gridview. but i am error...

Matt Watson 30/03/2016 22:19
In response to Exploring Prefix: A Free ASP.NET Profiling Tool
Glad you are loving it! Matt from Stackify...

Dmitry 28/03/2016 04:26
In response to Solved - The Microsoft.ACE.OLEDB.12.0 provider is not registered on the local machine
thank you about the VS 32-bit remark...

federico 26/03/2016 11:29
In response to Request.Form Is Empty When Posting To ASPX Page
thanks!....

Micheal 23/03/2016 00:58
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Thanks for the code. its pretty straightforward. worked for me on my first trial. Perfect!...

Francisco 22/03/2016 20:35
In response to ASP.NET MVC 5 with EF 6 - Working With Files
The post is very good, thanks...

Nick Brown 22/03/2016 13:53
In response to Adding A View
Hi, Many thanks for this tutorial, it's helping me get started with MVC. In VB (VS 2013) I get late...

ferry mae 22/03/2016 13:04
In response to Send form content by email in ASP.NET
do i need to change this? message.To.Add(new MailAddress("me@domain.com")); message.CC.Add(new you...

Keith 22/03/2016 12:02
In response to Creating a Connection String and Working with SQL Server LocalDB
As always worst explanation, but this time you rocked with plagiarism too .. huhh.. copied from Rick...