JSON Result in ASP.NET Core MVC

JSON Result in ASP.NET Core MVC

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

JSON Result in ASP.NET Core MVC

The JSON Result is one of the most important Action results in the ASP.NET Core MVC Application. This action result returns the data in JSON Format, i.e., key-value pairs. And moreover, we can also call this method using jQuery Ajax Request from a view.

In ASP.NET Core MVC, a JsonResult is an action result that allows you to return data in JSON format from a controller action. This is commonly used when you want to provide data to the client side of your application, such as in AJAX requests or when building APIs.

Now, if you go to the definition of JosnResult, then 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 to 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:

In some cases, 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 with the name Product.cs, and 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 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); 
        }
    }
}

Note: Remember that when returning data as JSON, it’s a good practice to ensure that your classes and properties are correctly decorated with attributes like [JsonProperty] to control serialization behavior. Additionally, always handle potential errors and exceptions when returning JSON results to provide meaningful responses to clients.

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 output as expected, as shown in the below image.

Calling JsonResult Action Method using jQuery AJAX

Advantages and Disadvantages of JSON Result in ASP.NET Core MVC:

Here are the advantages and disadvantages of using JSON results in ASP.NET Core MVC:

Advantages of JsonResult:
  • Lightweight Data Transfer: JSON (JavaScript Object Notation) is a lightweight data-interchange format, making it efficient for transmitting data between a server and a client. JSON serialization is efficient and can help reduce the size of data transferred over the network.
  • JavaScript Integration: JSON is natively supported by JavaScript, making it easy to consume JSON data directly in client-side scripts.
  • 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.
  • Serialization Customization: ASP.NET Core provides flexibility in customizing JSON serialization settings, allowing you to tailor the output format to your specific needs.
  • Testing: JSON data is human-readable and easy to inspect, which simplifies debugging and troubleshooting data-related issues. It also facilitates unit testing when comparing expected and actual JSON outputs.
Disadvantages of JsonResult:
  • No View Rendering: Unlike ViewResult or PartialViewResult, JsonResult doesn’t involve the view engine, so you cannot take advantage of view templating and layout management.
  • Complex Content: While JSON is suitable for structured data, it might become challenging when dealing with complex content such as richly formatted documents or mixed content (e.g., HTML with embedded JavaScript).
  • Security Risks: JSON data is parsed and executed by JavaScript code, which can expose applications to security vulnerabilities like JSON injection and cross-site scripting (XSS) attacks if not properly sanitized.
  • Lack of Metadata: Unlike XML, JSON does not inherently support metadata attributes that can describe the data structure. This can sometimes make conveying additional information about the data more challenging.
  • Limited Data Types: JSON supports a limited set of data types (e.g., strings, numbers, arrays, objects, booleans, null), which might require workarounds for representing more complex or specialized data types.
  • Serialization Overhead: While JSON serialization is efficient, the process of converting .NET objects to JSON format can add some overhead, especially for large and complex objects.

In summary, JsonResult in ASP.NET Core MVC provides many advantages, especially for lightweight data transfer, API responses, and integration with JavaScript. However, it’s not suitable for rendering views, might have security risks if not handled properly, and has limitations in representing complex and mixed content. Carefully consider your application’s requirements when choosing to use JsonResult for data transmission.

Use Cases of JSON Result in ASP.NET Core MVC:

JsonResult in ASP.NET Core MVC is commonly used to return data in JSON format from controller actions. JSON (JavaScript Object Notation) is a lightweight and widely supported data-interchange format, making it ideal for various scenarios where data needs to be transmitted between the server and client applications. Here are some use cases of JsonResult in ASP.NET Core MVC:

  • Web APIs: ASP.NET Core Web APIs often use JsonResult to return data to clients that are making API requests. This allows the API to provide structured data, such as responses to GET, POST, PUT, or DELETE requests, in a format that’s easy for the client to consume.
  • Single-Page Applications (SPAs): SPAs built using front-end frameworks like Angular, React, or Vue.js frequently communicate with the server using AJAX requests. JsonResult is used to send data back to the SPA, allowing for dynamic updates without requiring a full-page refresh.
  • AJAX Calls: For traditional multi-page applications, JsonResult can be used to respond to AJAX requests initiated from JavaScript, providing data updates without reloading the entire page.
  • Data Retrieval: When fetching data from a database or another source, JsonResult can be used to return the retrieved data in JSON format, which the client application can then process.
  • Search Results: In scenarios where users perform searches or filtering on a webpage, the search results can be returned as JSON using JsonResult. This allows for efficient data retrieval and presentation.
  • Autocomplete Suggestions: When implementing autocomplete or suggestion features, JsonResult can be used to send back matching suggestions to the user’s input.
  • Data Visualization: For applications that display charts, graphs, or other data visualizations on the client side, JsonResult can provide the necessary data in a format that the visualization library understands.
  • Mobile Apps: When building mobile apps that communicate with the server, JsonResult can be used to send and receive data between the app and the server.
  • Cross-Platform Integration: JsonResult is particularly useful for integrating different parts of a system or different services that might be developed using different technologies. JSON’s broad compatibility ensures that data can be easily exchanged between these components.
  • Third-Party Integrations: When integrating with third-party services or APIs that expect or provide data in JSON format, JsonResult is essential for translating between your application’s data and the external service’s requirements.

In all these cases, the use of JsonResult allows for efficient, structured, and standardized data exchange between the server and the client, enabling responsive and interactive user experiences.

In the next article, I am going to 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 *