JSON Result in ASP.NET MVC

JSON Result in ASP.NET MVC

In this article, I am going to discuss the JSON Result in the ASP.NET MVC application. Please read our previous article as we are going to work with the same example that we started in View Result and Partial View Result in ASP.NET MVC article, ASP.NET MVC has different types of Action Results. Each action result returns a different format of the output. As a programmer, we need to use different action results to get the expected output. Action Results return the result to the view page for the given request. 

JSON Result in ASP.NET MVC

The JSON result is one of the most important Action results in the ASP.NET MVC application. This action result returns the data in JSON Format i.e. in the form of key-value pairs. And moreover, we need to call this method using Ajax from a view. So, in my point of view, JSON Result is one of the coolest ActionResults. JsonResult is used to represent JSON-encoded data, which is most commonly used to return structured data to a calling script, especially in AJAX scenarios.

But that’s not why I like it so much. In ASP.NET MVC, you can JSONify anything.  For example, Let’s modify the Home Controller as shown below

public class HomeController : Controller
{
    [HttpGet]
    public JsonResult Index()
    {
        return Json(new { Name = "John Smith", ID = 4, DateOfBirth = new DateTime(1999, 12, 31) });
    }
}

Now, run the application and navigates to Home/Index in the URL and you will get the following error.

File Result, Content Result, Empty Result, JavaScript Result and JSON Result in ASP.NET MVC application

Here, as you can see, MVC Framework throwing an exception saying thatThis request has been blocked because sensitive information could be disclosed to third party websites when this is used in a GET request.

MVC is trying to protect you here; it doesn’t want you to share JSON information over a GET request because it could potentially contain sensitive information. This is attempting to protect you from an exploit known as JSON Hijacking. You can turn off this error by modifying the Index method as shown below.

public class HomeController : Controller
{
    [HttpGet]
    public JsonResult Index()
    {
        return Json(new { Name = "John Smith", ID = 4, DateOfBirth = new DateTime(1999, 12, 31) },
            JsonRequestBehavior.AllowGet);
    }
}

OUTPUT: {“Name”:”John Smith”,”ID”:4,”DateOfBirth”:”\/Date(946578600000)\/”}

JsonRequestBehavior.AllowGet does exactly what it sounds like; it allows the browsers to access JSON information in a GET request. I would only recommend turning this on if you know what you are doing since it could potentially expose you to JSON Hijacking. There are six overloaded versions available for this JSON as shown in the below image.

Json Results Overloaded Version in ASP.NET MVC Application

Parameters:
  1. data: The JavaScript object graph to serialize.
  2. contentType: The content type (MIME type).
  3. contentEncoding: The content-encoding.
  4. behavior: The JSON request behavior.
JSON with Complex Type in ASP.NET MVC Application:

First Create a Model in the Models folder with the name Person.cs and then copy and paste the following code into it.

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
Modify Home Controller:

Copy and paste the following code in Home Controller

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
           var persons = new List<Person>  
           {  
                new Person{Id=1, FirstName="Harry", LastName="Potter"},  
                new Person{Id=2, FirstName="James", LastName="Raj"}  
           };
           return Json(persons, "application/json", System.Text.Encoding.UTF8 ,JsonRequestBehavior.AllowGet);
    }
}

Output: [{“Id”:1,”FirstName”:”Harry”,”LastName”:”Potter”},{“Id”:2,”FirstName”:”James”,”LastName”:”Raj”}]

While returning more data in JSON format, there is a need to mention the maximum length. Assign the maximum length of data Using “MaxJsonLength” property as shown in the below code.

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
            var persons = new List<Person>  
            {  
                new Person{Id=1, FirstName="Harry", LastName="Potter"},  
                new Person{Id=2, FirstName="James", LastName="Raj"}  
            };

            var jsonResult = Json(persons, "application/json", System.Text.Encoding.UTF8 ,JsonRequestBehavior.AllowGet);
            jsonResult.MaxJsonLength = int.MaxValue;
            return jsonResult;
    }
}

In the next article, I am going to discuss FileResult in ASP.NET MVC Application. Here, in this article, I try to explain JSON Result in ASP.NET MVC application with examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article. 

Leave a Reply

Your email address will not be published.