Introduction

This article uses a simple example to answer some common questions when working on JSON objects in jQuery and MVC.

Background

"JSON" (JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. When working together with "jQuery" and "ASP.NET MVC" in building web applications, it provides an efficient mechanism to exchange data between the web browser and the web server.

At the browser side, the data is stored and manipulated as "JavaScript" "JSON objects". At the server side, if ASP.NET MVC is used, the data is stored and manipulated as ".NET objects".

When the browser loads data from the server, the .NET objects need to be "serialized" into "JSON strings" and passed to the browser. The browser will "de-serialize" the "JSON strings" into easy to use JavaScript "JSON objects".

How to initiate a request from the browser to the server to ask for some data as JavaScript "JSON objects"?

How does the server serialize the ".NET objects" and send them to the browser?

How does the browser serialize the JavaScript "JSON objects" and send them to the server?

How does the server "de-serialize" the "JSON strings" into ".NET objects"?

Besides answering these questions, this example project also shows how session can be used in "ASP.NET MVC" outside the "controllers". The simple example project looks like the following in Solution Explorer:

The main building blocks of the application are the following:

The class definitions of the .NET objects, which will also serve as the templates for the JSON objects that are implemented in the "Models\StudentModel.cs" file.

The "ASP.NET MVC" ViewPageIndex.aspx. It is the only ViewPage in the web application. All the client side JavaScript code is implemented in this page.

Two controller classes in the Controllers folder. The HomeController class is the Controller that loads Index.aspx. The JsonOperationsController class is the center place at the server side to process the JSON objects posted from the browsers and to deliver all the JSON objects to the browsers.

The StudentsRepository class serves as the repository of the application's data using the web application's session state.

This example project is developed in Visual Studio 2010 and "MVC 2". The jQuery version is "1.4.2". To build the UI of the application in Index.aspx, the "jQuery treeview plug-in" is used. This "plug-in" is used to display the application's data in a tree structure in the browser. This article assumes the readers having some basic knowledge on MVC, jQuery, and JSON. If you are new to these subjects, you should be able to easily find reference materials.

We will first take a look at the model classes in this application, so you will know the data being passed between the browser and the server. We will then take a look at the server side and the client side code. At the end, we will give answers to our questions to conclude this article.

The .NET "model" classes

In order to make the structure of the data being passed between the browser and the server complex enough, three .NET classes are implemented in the StudentModel.cs file:

These three classes are Student, Class, and Exam. The data being passed between the browser and the server are Lists of Student objects. Each Student object can have multiple Class objects referenced by the public "property" ClassesTaken, and each Class object can have multiple Exam objects referenced by the public propertyExamesTaken.

The StudentsRepository class

To demonstrate web session can be used outside MVC "controllers", the application data at the server side is kept in the session by the StudentsRepository class:

Three public methods are implemented in the "StudentsRepository" class:

The method Initialize is to initialize a List of Student objects by some randomly generated data according to the input parameters. The randomly generated Student "List" is then saved into the session state.

The method GetStudents returns the Student "List" retrieved from the session.

The method SetStudents takes a Student "List" from the input parameter and saves it into the session.

The GetStudents method takes an integer input and returns a List of Student objects to the browser.

The AddAnExamByJson method takes a List of Student objects from the browser and adds an Exam object to each "Class" object taken by the students. It saves the List into the session and then returns the List of the Student objects back to the browser.

The AddAnExamBySession method takes no parameter. It gets the List of Student objects from the web session using the StudentsRepository class. It adds an Exam object to each "Class" taken by the students, and returns the List of Student objects to the browser.

All the three methods send JSON objects to the browser using JsonResult. Each of them shows one of the three cases when receiving data from the browser.

The HTML part of Index.aspx is very simple, but you should give some attention to the following components:

The button control btnAddAnExamSession. This button triggers a "jQuery" AJAX call to the AddAnExamBySession method in JsonOperationsController.

The button control "btnAddAnExamJson. This button triggers a "jQuery" AJAX call to the AddAnExamByJson method in JsonOperationsController.

The divStudentTree is the place holder where we will be displaying the List of the Student objects received from the server using the jQuery treeview plug-in.

The majority of the logic in Index.aspx is implemented in JavaScript with jQuery:

In the $(document).ready() event, a synchronous AJAX call is made to the GetStudents method in JsonOperationsController using jQuery. The returned List of Student objects is already "de-serialized" into an array of JSON objects by jQuery. This JSON array is then saved in the global JavaScript variable StudentJson to be processed later. It is also used by the function buildStudentTree to build a treeview. The treeview is built on top of the StudentTreediv using the jQuery treeview plug-in.

In the click event of the btnAddAnExamSession button, an asynchronous AJAX call is made to the AddAnExamBySession method in JsonOperationsController. The treeview is then refreshed by the newly received student list.

In the click event of the btnAddAnExamJson button, an asynchronous AJAX call is made to the AddAnExamByJson method in JsonOperationsController. The treeview is then refreshed by the newly received student list.

The JavaScript code in Index.aspx demonstrates the following:

The jQuery "AJAX" calls can be made "synchronous" and "asynchronous". The default is an asynchronous call, but you can specify "async: false" to make it synchronous. Making a synchronous jQuery "AJAX" call is not the focus of this article, but it may be useful under certain circumstances.

Each of the three jQuery "AJAX" calls demonstrates one of the three cases, i.e., passing no data to the server, passing a scalar data item to the server, and passing an array of JSON objects to the server.

The add-on to the default MVC "Model Binder"

Now we have finished the coding on both the client and server sides to show how to work on JSON objects with jQuery and MVC. For the most part, it would work fine. But the default MVC "ModelBinder" does not de-serialize arrays of JSON objects. This means that we will fail to send the array of StudentJSON objects to the AddAnExamByJson method. To address this problem, we need to make changes to the "Global.asax.cs" file:

In Global.asax.cs, a class JsonModelBinder is implemented. The BindModel method in this class first checks the "content type" of the HTTP request. If it is "application/json", JavaScriptSerializer is used to de-serialize the posted content. Otherwise, the default "serializer" is used, so it will not alter the normal MVC behavior. I learned this technique from here. If you are interested, you can take a further look at it.

Run the application

Now we are ready to test run the application. At the time when Index.aspx loads, a synchronous jQuery "AJAX" call is made to retrieve a list of student JSON objects from the server by calling the GetStudents method in JsonOperationsController. The list of students is then displayed in a treeview by the jQuery treeview plug-in:

We can then click on the buttons "Add an exam to students by posting JSON" and "Add an exam to students using session". Each button click will issue an asynchronous jQuery "AJAX" call, either to the method AddAnExamByJson or the method AddAnExamBySession in JsonOperationsController. The treeview is refreshed with the new content:

From the above screenshot, we can see that the JSON objects are successfully posted to JsonOperationsController, and the session state managed by the StudentsRepository class also works properly.

Conclusion

To conclude this article, I will be answering the questions listed at the beginning:

How to initiate a request from the browser to the server to ask for some data as JavaScript JSON objects?

There are many ways to exchange data with JSON between the browser and the server. The method introduced in this article is just one of them. When working with jQuery and MVC, I believe that the method introduced here is a simple method among them.

I hope you like my postings, and I hope this article can help you one way or the other.