Thursday, December 24, 2020

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

  1. {  
  2.     "Books": [{  
  3.             "name""Asp.Net Mvc",  
  4.             "code""111"  
  5.         },  
  6.         {  
  7.             "name""Angular Js",  
  8.             "code""112"  
  9.         },  
  10.         {  
  11.             "name""Javascript",  
  12.             "code""113"  
  13.         },  
  14.         {  
  15.             "name""CLR",  
  16.             "code""114"  
  17.         }  
  18.     ]  
  19. }; 
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.
  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 {  
  11.                         Name: "Suraj Sahoo",  
  12.                         EmpCode: "EMP042"  
  13.                     },  
  14.                     new Employee {  
  15.                         Name: "Suraj Sharma",  
  16.                         EmpCode: "EMP044"  
  17.                     },  
  18.                     new Employee {  
  19.                         Name: "Suraj Ray",  
  20.                         EmpCode: "EMP041"  
  21.                     }  
  22.                 };  
  23.                 public ActionResult Index() {  
  24.                     return View();  
  25.                 }  
  26.                 public JsonResult GetEmployeeDataJson(string empCode) {  
  27.                     var employee = employeeData.Where(emp =>  
  28.                         emp.EmpCode == empCode).SingleOrDefault();  
  29.                     return Json(employee, JsonRequestBehaviour.AllowGet);  
  30.                 } 
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:
  1. {  
  2.     "EmployeeId": 0,  
  3.     "Name""Suraj Sahoo",  
  4.     "EmpCode""042",  
  5.     "IsActiveEmployee"false,  
  6.     "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.

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...