Working with JSON in MVC


JSON Java Script Object Notation is a very familiar and commonly used concept. It is a data interchange medium and is very lightweight. It is one kind of a syntax for storing and passing data. Since it is Java script object notation, it uses the java script style of syntax, but actually is text only. It also is language independent. The format would look like below: 

  1. {"Books":[       
  2.                {"name":"Asp.Net Mvc""code":"111"},   
  3.                {"name":"Angular Js""code":"112"},   
  4.                {"name":"Javascript""code":"113"},  
  5.                 {"name":"CLR""code":"114"}     
  6.  ]};   
Now this JSON object can be created and used to POST or GET in MVC application. Usually, when we do an ajax call, we get the HTML fragments and send them to the browser or append to any DOM elements. That is acceptable, but sending HTML elements with data is not advisable, so wouldn't it be great to send data in a specific format and the browser assigns the data into the HTML. Here, JSON comes in handy. Let's see how. I will explain in simple terms and snippets for better understanding as this topic is not complex at all.

Peek into Snippets!!

I will proceed with an anticipation that readers are aware of MVC (Model, View & Controller), as I will not be sharing the steps to create an MVC project. So, let's start.

When we create a controller in an MVC project, we know the default type added is ActionResult, which is generic to other types of method types pre-defined like: ViewResult, JsonResult, etc.. Thus, for returning a JSON data, we can use either ActionResult or JsonResult, but preferably use JsonResult as we already know the type, the method will return. JsonResult is actually a special ActionResult, which suggests the ViewEngine that an object of JSON type will be returned rather than normal HTML.

Let's see the snippet and then try and understand.

  1. using System;  
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Web;   
  5. using System.Web.MVC;   
  6. using DemoJsonTest.Models;   
  7.      namespace DemoJsonTest.Controllers {   
  8.            public class EmployeeController : Controller {  
  9.                    private Employee[] employeeData = {  
  10.                          new Employee {Name:"Suraj Sahoo",EmpCode:"EMP042"},  
  11.                          new Employee {Name:"Suraj Sharma",EmpCode:"EMP044"},                  
  12.                          new Employee {Name:"Suraj Ray",EmpCode:"EMP041"}           
  13.                     };  
  14.            public ActionResult Index() {  
  15.                      return View();    
  16.            }      
  17.            public JsonResult GetEmployeeDataJson(string empCode) {    
  18.                      var employee = employeeData.Where(emp =>   
  19.                                                emp.EmpCode == empCode).SingleOrDefault();           
  20.                      return Json(employee, JsonRequestBehaviour.AllowGet);       
  21.             }   
Thus, in the above code, we have shown a normal controller, in whose constructor we have explicitly initialized a model named Employee with some dummy data. Then the main part is the JsonReult method using which we are filtering the data based on the parameters passed, here EmpCode and then returning the Json object. Mark here, we have used JsonRequestBehaviour.AllowGet. Now what's this? This has an interesting concept behind it. Usually, the browsers to avoid malicious sites trying to intercept JSON dat are returned, in response to a GET request, it does not respond to GET requests by default.

System.InvalidOperationException: This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

The above is a part of the error thrown when we miss AllowGet. That is self explanatory actually.

We usually use ajax options, i.e. success method, to process the JSON data received from the GET request and append or set to the HTML DOM elements.

Thus, in the above snippet, we are fetching the data in JSON format from the GET response and binding to the table html dom.

A point to note here is that, when we assign/cast (actually) a model into JSON object and we explicitly specify few properties of the model and miss out on others, MVC framework is clever enough to first convert the model with each property into JSON and then assign default values to those properties which we have missed. Lets see an example of conversion:

  1. "EmployeeId":0, "Name":"Suraj Sahoo""EmpCode":"042""IsActiveEmployee"false"DepartmentId"null }   
Mark here,that we have only specified the values of Name and the EmpCode, all other values assigned after JSON conversion by the MVC smart framework.


We saw and discussed a very simple and interesting topic regarding the JSON in MVC and how smartly MVC handles the conversion. This helps when we use API and then return JSON,XML to interchange and expose our data. JSON is actually an alternative to an XML form of data exchange. For angular JS nowadays which is in demand, we use the API controller, return JSON data and take advantage of Angular two-way binding.

I hope this helps the beginners out there learning MVC. This is a part of it. Enjoy coding. I'm open to suggestions. Don't forget to add your feedback.

Read more articles on JSON:

Up Next
    Ebook Download
    View all
    View all