JSON Result in ASP.NET Core MVC

JSON Result in ASP.NET Core MVC

In this article, I will discuss the JSON Result in ASP.NET Core MVC Web Application with Examples. Please read our previous article about the Partial View Result in ASP.NET Core MVC Application.

JSON Result in ASP.NET Core MVC

In ASP.NET Core MVC, a JsonResult represents an HTTP response containing JSON data (i.e., key-value pairs). It is used when we want to return JSON-formatted data from a controller action method to the client. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate.

When we return a JsonResult from a controller action, ASP.NET Core MVC serializes the specified data into JSON format and sends it back to the client as the HTTP response body. This is commonly used for AJAX requests where the client-side JavaScript code expects to receive data in JSON format or when building APIs. 

Now, if you go to the definition of JosnResult, you will see the following signature. This class has two constructors, a few properties, and an overriding ExecuteResultAsync method.

JSON Result in ASP.NET Core MVC

How does the ExecuteResultAsync Method of the JsonResult class Work in ASP.NET Core MVC?

The ExecuteResultAsync method executes the result of an action method that returns JSON data. Here is how the ExecuteResultAsync method works within the JsonResult class:

  • Data Serialization: Before ExecuteResultAsync is called, the JSON data to be returned is typically set within the Value property of the JsonResult object. This data can be any object or primitive type that can be serialized into JSON format.
  • Execution: When the action method returns a JsonResult object, the ASP.NET Core MVC framework calls the ExecuteResultAsync method of that JsonResult object.
  • Serialization and Output: Within the ExecuteResultAsync method, the JSON data set in the Value property is serialized into a JSON string using the configured JSON serializer (typically Newtonsoft.Json or System.Text.Json). Once serialized, this JSON string is written to the response body, along with appropriate HTTP headers indicating that the content is JSON.
How Do We Use JsonResult in ASP.NET Core MVC?

In ASP.NET Core MVC, you can use the JsonResult class to return data in JSON format from your controller actions. First, create a controller action that will return the JSON data as follows:

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public JsonResult Index()
        {
            var jsonData = new { Name = "Pranaya", ID = 4, DateOfBirth = new DateTime(1988, 02, 29) }
            return new JsonResult(jsonData);
        }
    }
}
Using JsonResult Helper Method:

Alternatively, you can use the Json helper method provided by the Controller class to create a JsonResult. This method is commonly used to simplify the creation of JSON results:

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public JsonResult Index()
        {
            var jsonData = new { Name = "Pranaya", ID = 4, DateOfBirth = new DateTime(1988, 02, 29) }
            return Json(jsonData);
        }
    }
}
Returning a Collection of Objects:
using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public JsonResult Index()
        {
            var jsonArray = new[]
            {
                new { Name = "Pranaya", Age = 25, Occupation = "Designer" },
                new { Name = "Ramesh", Age = 30, Occupation = "Manager" }
            };

            return Json(jsonArray);
        }
    }
}
Specifying JSON Serializer Settings:

You can also customize the JSON serialization settings, such as formatting and property name handling:

using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public JsonResult Index()
        {
            //Converting Key Name to Pascal case, by default it is Camel Case
            var options = new JsonSerializerOptions();
            options.PropertyNamingPolicy = null;
            
            var jsonArray = new[]
            {
                new { Name = "Pranaya", Age = 25, Occupation = "Designer" },
                new { Name = "Ramesh", Age = 30, Occupation = "Manager" }
            };

            return Json(jsonArray, options);
        }
    }
}
Using Implicit JSON Result:

Sometimes, you don’t need to return a JsonResult instance explicitly. ASP.NET Core can automatically serialize objects to JSON when you return them directly:

using Microsoft.AspNetCore.Mvc;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            var jsonArray = new[]
            {
                new { Name = "Pranaya", Age = 25, Occupation = "Designer" },
                new { Name = "Ramesh", Age = 30, Occupation = "Manager" }
            };

            return Ok(jsonArray); // This will be automatically serialized to JSON
        }
    }
}
JSON with Complex Type in ASP.NET Core MVC Application:

First, Create a Model in the Models folder named Product.cs, then copy and paste the following code into it.

namespace ActionResultInASPNETCoreMVC.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public string? Description { get; set; }
    }
}
Modify Home Controller:

Copy and paste the following code into the Home Controller.

using ActionResultInASPNETCoreMVC.Models;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Serialization;
using System.Text.Json;
namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public JsonResult Index()
        {
            //Converting Key Name to Pascal case, by default it is Camel Case
            var options = new JsonSerializerOptions();
            options.PropertyNamingPolicy = null;

            List<Product> products = new List<Product>
            {
                new Product{ Id = 1001, Name = "Laptop",  Description = "Dell Laptop" },
                new Product{ Id = 1002, Name = "Desktop", Description = "HP Desktop" }
            };

            return Json(products, options); 
        }
    }
}
Calling JsonResult Action Method using jQuery AJAX:

Now, let us try to understand how we can call an action method in ASP.NET Core MVC, which returns JSON data using jQuery AJAX. So, first, modify the Home Controller as follows:

using ActionResultInASPNETCoreMVC.Models;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;

namespace ActionResultInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }

        public ActionResult Details(string Category)
        {
            //Converting Key Name to Pascal case, by default it is Camel Case
            var options = new JsonSerializerOptions();
            options.PropertyNamingPolicy = null;

            try
            {
                //Based on the Category Fetch the Data from the database 
                //Here, we have hard coded the data
                List<Product> products = new List<Product>
                {
                    new Product{ Id = 1001, Name = "Laptop",  Description = "Dell Laptop" },
                    new Product{ Id = 1002, Name = "Desktop", Description = "HP Desktop" },
                    new Product{ Id = 1003, Name = "Mobile", Description = "Apple IPhone" }
                };
                //Please uncomment the following two lines if you want see what happend when exception occurred
                //int a = 10, b = 0;
                //int c = a / b;
                return Json(products, options);
            }
            catch(Exception ex) 
            {
                return new JsonResult(new { Message = ex.Message, StackTrace = ex.StackTrace, ExceptionType = "Internal Server Error" }, options)
                {
                    StatusCode = StatusCodes.Status500InternalServerError // Status code here 
                };
            }
        }
    }
}

Next, modify the Index.cshtml view as follows:

@{
    ViewData["Title"] = "Home Page";
    Layout = null;
}

<div>
    <table id="tblProducts" class="tblProducts">
        <thead>
            <tr>
                <th align="left" class="productth">ProductID</th>
                <th align="left" class="productth">ProductName</th>
                <th align="left" class="productth">Descrtption</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>

<script>
    $(document).ready(function () {
        $("#tblProducts tbody tr").remove();
        var rawdata = { 'Category': 'Electronics' };
        $.ajax({
            type: "GET",
            url: "/Home/Details/",
            data: rawdata,
            dataType: 'json',
            success: function (data) {
                var items = '';
                $.each(data, function (i, item) {
                    var rows = "<tr>"
                        + "<td class='prtoducttd'>" + item.Id + "</td>"
                        + "<td class='prtoducttd'>" + item.Name + "</td>"
                        + "<td class='prtoducttd'>" + item.Description + "</td>"
                        + "</tr>";
                    $('#tblProducts tbody').append(rows);
                });
            },
            error: function (errorData) {
                //respone will be returned here
                alert(errorData);
                var ErrorResponse = jQuery.parseJSON(errorData.responseText);
                alert("Message: " + ErrorResponse.Message);
                alert("StackTrace: " + ErrorResponse.StackTrace);
                alert("ExceptionType: " + ErrorResponse.ExceptionType);
            }
        });
    });
</script>

Now, run the application, and you should get the expected output, as shown in the image below.

Calling JsonResult Action Method using jQuery AJAX

Why JSON Result in ASP.NET Core MVC?
  • Lightweight Data Transfer: JSON (JavaScript Object Notation) is a lightweight data-interchange format that efficiently transmits data between a server and a client. JSON serialization is efficient and can help reduce the data transfer size over the network.
  • API Responses: JSON is the standard format for many Web APIs, making it a natural choice for building RESTful APIs in ASP.NET Core Web API projects.
  • Client Compatibility: JSON is widely supported across various programming languages and platforms, making it easy to consume JSON data in different client applications, such as web browsers, mobile apps, and desktop applications.

In the next article, I will discuss the Content Result of ASP.NET Core MVC Application. In this article, I try to explain the JSON Result in ASP.NET Core MVC Application with Examples. I hope you enjoy this Json Result in ASP.NET Core MVC Application article.

Leave a Reply

Your email address will not be published. Required fields are marked *