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