Click here to Skip to main content
15,897,273 members
Articles / Programming Languages / Javascript

Working with JSON in MVC

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
2 Apr 2016CPOL3 min read 7.3K   5  
Working with JSON in MVC

Introduction

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 JavaScript object notation, it uses the JavaScript style of syntax, but actually is text only. It also is language independent. The format would look like below:

C#
{"Books":[
    {"name":"Asp.Net Mvc", "code":"111"},
    {"name":"Angular Js", "code":"112"},
    {"name":"Javascript", "code":"113"},
    {"name":"CLR", "code":"114"}
]}

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 would not that 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.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.MVC;
using DemoJsonTest.Models;

namespace DemoJsonTest.Controllers {
    public class EmployeeController : Controller {
        private Employee[] employeeData = {
            new Employee {Name:"Suraj Sahoo",EmpCode:"EMP042"},
            new Employee {Name:"Suraj Sharma",EmpCode:"EMP044"},
            new Employee {Name:"Suraj Ray",EmpCode:"EMP041"}
        };

    public ActionResult Index() {
        return View();
    }
   
    public JsonResult GetEmployeeDataJson(string empCode) {
        var employee = employeeData.Where(emp => emp.EmpCode == empCode).SingleOrDefault();
        return Json(employee, JsonRequestBehaviour.AllowGet);
    }

Thus, in the above code, we have shown a normal controller, in whose constructor we have explicitly initialized a model named Employee with few dummy data. Then the main part is the JsonReult method using which, we are filtering the data based on the parameter 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 data 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.

C#
<script type="text/javascript">
$.ajax({
    url: "GET REQUEST URL",
    type:"GET",
    success: function(empData) {
            var trgt = $("#tblEmployee");
            target.append("<tr><td>" + empData.Name + 
            "</td><td>" + empData.EmpCode + "</td></tr>");
        },
    error: function() {
      //Do something..
        }

});
// ]]></script>

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. Let's see an example of conversion:

C#
{ "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.

Conclusion

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 XML form of data exchange. For angular JS, now a days which is in demand, we use the API controller, return JSON data and take advantage of Angular two-way binding.
I hope this helps beginners out there learning MVC. This is a part of it. Enjoy coding. I am open to suggestions. Don’t miss adding your feedback. :)

This article was originally posted at http://surajpassion.in/working-with-json-in-mvc

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --