About

JsonResult is an ActionResult type in MVC. It helps to send the content in JavaScript Obect Notation (JSON) format.

History

To learn more about ActionResult and some of the other following action result types, please go through the following articles in my blog.

  1. Action Result

  2. View Result

  3. Partial View Result with sample application

  4. Prevent PartialView to access directly from the URL

RoadMap

In this article, you will get an idea of the following things.

  1. About JsonResult and its properties

    • ContentEncoding

    • ContentType

    • Data

    • JsonRequestBehavior

    • MasJsonLength

    • RecursionLimit

  2. Sample project with various scenarios using JsonResult:

    • Send JSON content welcome note based on user type

    • Get the list of users in JSON Format

    • How to create JSON data at the client side and send it to the controller

    • How to handle a huge amount of JSON Data

  1. Unit Testing of JsonResult

About JsonResult and its properties

The JSON format is an open standard format. The format of data looks very easy to understand and the data objects consist of attribute-value pairs.

ContentEncoding: It helps to indicate the content encoding type, the default encoding for JSON is UTF-8.

ContentType: It helps to indicate the content type. The default content type for JSON is application/json; charset=utf-8.

Note: ContentType and ContentEncoding are not necessary to mention when sending the data in JSON format as the HTTP headers are having a responsibility to tell the recipient what kind of content they're dealing with.

Data: This indicates what the content data is, that means what you will send in JSON format.

JsonRequestBehavior: This property has two options. Those are AllowGet and DenyGet. The default option is DenyGet. When you send data in JSON format, using Get Request, it's necessary to specify the property as AllowGet otherwise it shows the error as “The request would be blocked since the JSON data is considered as sensitive data information”.

MaxJsonLength: This helps to get or set the maximum JSON content length that you will send. The default value for this is 2097152 characters, that is equal to 4 MB of Unicode string data. You can even increase the size based if needed, for that you will get an idea later in this article.

RecursionLimit: Indicates the constraining number of object levels to process. The default value is 100. It means you can serialize the objects that are nested to a depth of 100 objects referencing each other. In a general scenario the default limit 100 is obviously sufficient when you deal with a JsonResult so there is no need to increase it even though you have the option to increase the limit if required.

Sample Project with Various Scenarios by using JsonResult

Create a new project with the name JsonResultDemo and choose the template as MVC as shown in the following screen shots.

asp dotnet web application

Now, click on the OK button then the displayed screen is as in the following.

change authentication

As in the preceding template, you need to select the “Add Unit Tests” option as well. So It helps to create a Unit Test project and then again click on the OK button then the project will be created and the startup application page displayed like the following.

your asp application

Now, add a controller and provide the name as “JsonDemoController” as in the following.

t application

Click on the Controller and then it wil open the popup window as in the following.

mvc5 controller

Now click on the “Add” button and then it opens a popup to enter the name. So enter the name as “JsonDemoController” as shown in the screen shot.

add controller

After adding the controller to the project the controller page looks like the following.

json demo controller

Until now, you are done with the creation of the sample project template with the addition of one controller named “JsonDemoController”.

Scenario 1: Send JSON Content welcome note based on user type

In this scenario, you will learn how to send a simple welcome note message in JSON format from the controller. Now, replace the existing code with the following code in the JsonDemoController.cs file.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Web.Mvc;  
  5. using System.Web.Script.Serialization;  
  6. using JsonResultDemo.Models;  
  7.   
  8. namespace JsonResultDemo.Controllers  
  9. {  
  10.     public class JsonDemoController : Controller  
  11.     {  
  12.         #region ActionControllers  
  13.   
  14.         /// <summary>  
  15.         /// Welcome Note Message  
  16.         /// </summary>  
  17.         /// <returns>In a Json Format</returns>  
  18.         public JsonResult WelcomeNote()  
  19.         {  
  20.             bool isAdmin = false;  
  21.             //TODO: Check the user if it is admin or normal user, (true-Admin, false- Normal user)  
  22.             string output = isAdmin ? "Welcome to the Admin User" : "Welcome to the User";  
  23.   
  24.             return Json(output, JsonRequestBehavior.AllowGet);  
  25.         }  
  26.      }  

Then, build the application (F6) and then hit the F5 to run an application and then navigate to the following URL http://localhost:49568/JsonDemo/WelcomeNote (It might be a chance to get a different Port Id at your end).

Then the displayed screen looks like the following.

WelcomecomeNote

In this scenario, you now have an idea of how to send a simple string in JSON format.

Scenario 2: Get the list of users in JSON Format

In this scenario you will send a list of users in JSON format.

Step 1: Add a class file “UserModel.cs” like the following.

add new controller

Click on “Class” and then the displayed link is as the following.

add new class

Enter the name as “UserModel.cs” and then click on the Add button.

Step 2: Update the code in UserMode.cs with the following code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace JsonResultDemo.Models  
  7. {  
  8.     public class UserModel  
  9.     {  
  10.         public int UserId { getset; }  
  11.         public string UserName { getset; }  
  12.         public string Company { getset; }  
  13.     }  

Step 3: Add one method named GetUsers in the JsonDemoController.cs file that will return the list of sample users.
  1.         /// <summary>  
  2.         /// Get the Users  
  3.         /// </summary>  
  4.         /// <returns></returns>  
  5.         private List<UserModel> GetUsers()  
  6.         {  
  7.             var usersList = new List<UserModel>  
  8.             {  
  9.                 new UserModel  
  10.                 {  
  11.                     UserId = 1,  
  12.                     UserName = "Ram",  
  13.                     Company = "Mindfire Solutions"  
  14.                 },  
  15.                 new UserModel  
  16.                 {  
  17.                     UserId = 1,  
  18.                     UserName = "chand",  
  19.                     Company = "Mindfire Solutions"  
  20.                 },  
  21.                 new UserModel  
  22.                 {  
  23.                     UserId = 1,  
  24.                     UserName = "Abc",  
  25.                     Company = "Abc Solutions"  
  26.                 }  
  27.             };  
  28.   
  29.             return usersList;  
  30.         } 

Step 4: Create one Action Controller method named GetUsersData with the following code in the JsonDemoController.cs file.

  1. /// <summary>  
  2.         /// Get tthe Users data in Json Format  
  3.         /// </summary>  
  4.         /// <returns></returns>  
  5.         public JsonResult GetUsersData()  
  6.         {  
  7.             var users = GetUsers();  
  8.             return Json(users, JsonRequestBehavior.AllowGet);  
  9.         } 

Step 5: Run the application with this URL http://localhost:49568/JsonDemo/GetUsersData then the output looks like the following.

getuser data 

Scenario 3 : Create JSON data at the client side and send content to the controller

In this scenario, you will create JSON data at the client side and then that data will be sent to the Controller action. The controller action request type is HttpPost.

Step 1: Create one Action controller method named Sample like the following in the JsonDemoController.cs file.

  1. /// <summary>  
  2. /// Sample View  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. public ActionResult Sample()  
  6. {  
  7.     return View();  

Step 2: Create a View file named “Sample.cshtml” by right-clicking on View() in the Sample action controller method then click on “Add View” in the Sample action like the following.

json demo controller code

By clicking on Add View it opens a popup and deselects the "Use a layout page" option. It then should look as in the following.

 add new view

Now, click on the OK button then the sample.cshtml file will be created.

Step 3: Replace it with the following cshtml code in the sample.cshtml file.

  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6.   
  7. <html>  
  8.     <head>  
  9.         <meta name="viewport" content="width=device-width" />  
  10.         <title>Create Sample JSON Data and send it to controller</title>  
  11.     </head>  
  12.     <body>  
  13.         <div>  
  14.             <label>Create Sample User JSON Data and send it to controller</label><br/><br />  
  15.             <input type="button" id="btnUpdateUserDetail" value="Update User Detail" onclick="UpdateUserDetail();"/>  
  16.         </div>  
  17.     </body>  
  18. </html>  
  19. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  20. <script lang="en" type="text/javascript">  
  21.     function UpdateUserDetail() {  
  22.         var usersJson = GetSampleUsersList();  
  23.         var getReportColumnsParams = {  
  24.             "usersJson": usersJson  
  25.         };  
  26.         $.ajax({  
  27.             type: "POST",  
  28.             traditional: true,  
  29.             async: false,  
  30.             cache: false,  
  31.             url: '/JsonDemo/UpdateUsersDetail',  
  32.             context: document.body,  
  33.             data: getReportColumnsParams,  
  34.             success: function (result) {  
  35.                 alert(result);  
  36.             },  
  37.             error: function (xhr) {  
  38.                 //debugger;  
  39.                 console.log(xhr.responseText);  
  40.                 alert("Error has occurred..");  
  41.             }  
  42.         });  
  43.     }  
  44.     function GetSampleUsersList() {  
  45.         var userDetails = {};  
  46.         var usersList = [];  
  47.         for (var i = 1; i <= 3; i++) {  
  48.             userDetails["UserId"] = i;  
  49.             userDetails["UserName"] = "User- " + i;  
  50.             userDetails["Company"] = "Company- " + i;  
  51.             usersList.push(userDetails);  
  52.         }  
  53.         return JSON.stringify(usersList);  
  54.     }  
  55. </script> 

The following is a brief description of the Sample.cshtml file:

  • The HTML body contains a label, about, to describe the functionality and one input button with an onclick of the UpdateUserDetail() function.

  • The JavaScript part contains the jQuery reference and it contains two functions.

  • GetSampleUsersList() will return the sample users in a stringified JSON format.

  • UpdateUserDetail() sends the ajax request of post type for JsonDemoController with UpdateUserDetail action.

Step 4: A Create Action method named UpdateUsersDetail in the JsonDemoController as in the following and put a breakpoint in this method on the first line of code to help to trace the details.

  1. /// <summary>  
  2. /// Update the user details  
  3. /// </summary>  
  4. /// <param name="usersJson">users list in JSON Format</param>  
  5. /// <returns></returns>  
  6. [HttpPost]  
  7. public JsonResult UpdateUsersDetail(string usersJson)  
  8. {  
  9.     var js = new JavaScriptSerializer();  
  10.     UserModel[] user = js.Deserialize<UserModel[]>(usersJson);  
  11.   
  12.     //TODO: user now contains the details, you can do required operations  
  13.     return Json("User Details are updated");  

Step 5: Build and run the application (hit F5) with the URL ( http://localhost:49568/JsonDemo/Sample ) then the resultant screen looks like the following.

create sample user json data

Step 6: Now, click on the “Update User Detail” button as it appears in the aforesaid screenshot. Then the resultant screen looks like the following.

 update user detail
 
Step 7: Just review the preceding image, you can identify that you are able to send the JSON data to the controller action from the client side and as well as you have deserialized the JSON data and assigned that data to the UserModel entity.

Scenario 4: How to handle huge amount of JSON Data

In this scenario, you will get an idea of how to send a huge amount of JSON Data. Actually in certain scenarios you must send a huge amount of data from a controller to a view. In that case the following example will be helpful to you.

Step 1: Create one method named GetUsersHugeData() as in the following. It just helps to generate sample user data.

  1.         /// <summary>  
  2.         /// Get the huge list of users  
  3.         /// </summary>  
  4.         /// <returns></returns>  
  5.         private List<UserModel> GetUsersHugeData()  
  6.         {  
  7.             var usersList = new List<UserModel>();  
  8.             UserModel user;  
  9.             for (int i = 1; i < 51000; i++)  
  10.             {  
  11.                 user = new UserModel  
  12.                 {  
  13.                     UserId = i,  
  14.                     UserName = "User-"+i,  
  15.                     Company = "Company-"+i  
  16.                 };  
  17.                 usersList.Add(user);  
  18.             }  
  19.   
  20.             return usersList;  
  21.         } 

Step 2: Create an Action method named GetUsersHugeList() like the following in the JsonDemoController.cs file. 

  1. /// <summary>  
  2. /// Get the huge list of Users  
  3. /// </summary>  
  4. /// <returns></returns>  
  5. public JsonResult GetUsersHugeList()  
  6. {  
  7.     var users = GetUsersHugeData();  
  8.     return Json(users, JsonRequestBehavior.AllowGet);  


Step 3: Now, build and run (hit F5) the application with the URL ( http://localhost:49568/JsonDemo/GetUsersHugeList ) then the error screen appears like the following.

server error

Step 4: To fix the preceding error add the following code in the JsonDemoController file. This methods helps to update the MaxJsonLength property value to Int32.MaxValue. 

  1.  /// <summary>  
  2. /// Override the JSON Result with Max integer JSON lenght  
  3. /// </summary>  
  4. /// <param name="data">Data</param>  
  5. /// <param name="contentType">Content Type</param>  
  6. /// <param name="contentEncoding">Content Encoding</param>  
  7. /// <param name="behavior">Behavior</param>  
  8. /// <returns>As JsonResult</returns>  
  9. protected override JsonResult Json(object data, string contentType,  
  10.     Encoding contentEncoding, JsonRequestBehavior behavior)  
  11. {  
  12.     return new JsonResult()  
  13.     {  
  14.         Data = data,  
  15.         ContentType = contentType,  
  16.         ContentEncoding = contentEncoding,  
  17.         JsonRequestBehavior = behavior,  
  18.         MaxJsonLength = Int32.MaxValue  
  19.     };  


In the same way, you can increase the RecursionLimit property value. Also if you require JsonData with a depth (nested levels) greater than 100.

Step 5: Now, build and run (hit F5) the application with the URL ( http://localhost:49568/JsonDemo/GetUsersHugeList ) and then the huge data result appears instead of an error.

getusershugelist

I have provided the formatted complete code for the JsonDemoController.cs file for what you have done until now in the aforesaid scenarios.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Web.Mvc;  
  5. using System.Web.Script.Serialization;  
  6. using JsonResultDemo.Models;  
  7.   
  8. namespace JsonResultDemo.Controllers  
  9. {  
  10.     public class JsonDemoController : Controller  
  11.     {  
  12.         #region ActionControllers  
  13.   
  14.         /// <summary>  
  15.         /// Welcome Note Message  
  16.         /// </summary>  
  17.         /// <returns>In a JSON Format</returns>  
  18.         public JsonResult WelcomeNote()  
  19.         {  
  20.             bool isAdmin = false;  
  21.             //TODO: Check the user if it is admin or normal user, (true-Admin, false- Normal user)  
  22.             string output = isAdmin ? "Welcome to the Admin User" : "Welcome to the User";  
  23.   
  24.             return Json(output, JsonRequestBehavior.AllowGet);  
  25.         }  
  26.   
  27.         /// <summary>  
  28.         /// Get tthe Users data in JSON Format  
  29.         /// </summary>  
  30.         /// <returns></returns>  
  31.         public JsonResult GetUsersData()  
  32.         {  
  33.             var users = GetUsers();  
  34.             return Json(users, JsonRequestBehavior.AllowGet);  
  35.         }  
  36.   
  37.         /// <summary>  
  38.         /// Sample View  
  39.         /// </summary>  
  40.         /// <returns></returns>  
  41.         public ActionResult Sample()  
  42.         {  
  43.             return View();  
  44.         }  
  45.   
  46.         /// <summary>  
  47.         /// Update the user details  
  48.         /// </summary>  
  49.         /// <param name="usersJson">users list in JSON Format</param>  
  50.         /// <returns></returns>  
  51.         [HttpPost]  
  52.         public JsonResult UpdateUsersDetail(string usersJson)  
  53.         {  
  54.             var js = new JavaScriptSerializer();  
  55.             UserModel[] user = js.Deserialize<UserModel[]>(usersJson);  
  56.   
  57.             //TODO: user now contains the details, you can do required operations  
  58.             return Json("User Details are updated");  
  59.         }  
  60.           
  61.         /// <summary>  
  62.         /// Get the huge list of Users  
  63.         /// </summary>  
  64.         /// <returns></returns>  
  65.         public JsonResult GetUsersHugeList()  
  66.         {  
  67.             var users = GetUsersHugeData();  
  68.             return Json(users, JsonRequestBehavior.AllowGet);  
  69.         }  
  70.  
  71.         #endregion  
  72.  
  73.  
  74.         #region Methods  
  75.   
  76.         /// <summary>  
  77.         /// Get the Users  
  78.         /// </summary>  
  79.         /// <returns></returns>  
  80.         private List<UserModel> GetUsers()  
  81.         {  
  82.             var usersList = new List<UserModel>  
  83.             {  
  84.                 new UserModel  
  85.                 {  
  86.                     UserId = 1,  
  87.                     UserName = "Ram",  
  88.                     Company = "Mindfire Solutions"  
  89.                 },  
  90.                 new UserModel  
  91.                 {  
  92.                     UserId = 1,  
  93.                     UserName = "chand",  
  94.                     Company = "Mindfire Solutions"  
  95.                 },  
  96.                 new UserModel  
  97.                 {  
  98.                     UserId = 1,  
  99.                     UserName = "Abc",  
  100.                     Company = "Abc Solutions"  
  101.                 }  
  102.             };  
  103.   
  104.             return usersList;  
  105.         }  
  106.   
  107.         /// <summary>  
  108.         /// Get the huge list of users  
  109.         /// </summary>  
  110.         /// <returns></returns>  
  111.         private List<UserModel> GetUsersHugeData()  
  112.         {  
  113.             var usersList = new List<UserModel>();  
  114.             UserModel user;  
  115.             for (int i = 1; i < 51000; i++)  
  116.             {  
  117.                 user = new UserModel  
  118.                 {  
  119.                     UserId = i,  
  120.                     UserName = "User-"+i,  
  121.                     Company = "Company-"+i  
  122.                 };  
  123.                 usersList.Add(user);  
  124.             }  
  125.   
  126.             return usersList;  
  127.         }  
  128.   
  129.         /// <summary>  
  130.         /// Override the Json Result with Max integer JSON lenght  
  131.         /// </summary>  
  132.         /// <param name="data">Data</param>  
  133.         /// <param name="contentType">Content Type</param>  
  134.         /// <param name="contentEncoding">Content Encoding</param>  
  135.         /// <param name="behavior">Behavior</param>  
  136.         /// <returns>As JsonResult</returns>  
  137.         protected override JsonResult Json(object data, string contentType,  
  138.             Encoding contentEncoding, JsonRequestBehavior behavior)  
  139.         {  
  140.             return new JsonResult()  
  141.             {  
  142.                 Data = data,  
  143.                 ContentType = contentType,  
  144.                 ContentEncoding = contentEncoding,  
  145.                 JsonRequestBehavior = behavior,  
  146.                 MaxJsonLength = Int32.MaxValue  
  147.             };  
  148.         }  
  149.  
  150.         #endregion  
  151.     }  


You now have an idea of how to use a JsonResult type in MVC application with various scenarios. Now, it's time to test the controller action methods using the JsonDemoController.Test project.

Unit Testing the JsonResult in MVC

The main feature of MVC applications is it supports the Test Data Driven (TDD) approach. Since the Controller file is just a kind of class file, it's easy to implement the Test methods in the Test Project. Now you will learn how to test the JsonResult methods in the test project.

Step 1: Add a class file named “JsonDemoControllerTest.cs” to the JsonResultDemo.Tests projects like the following.

controller

Click on “Class” to open a popup like the following and then update the name as “JsonDemoControllerTest.cs”.

json demo controller test

Step 2: After clicking on the “Ok” button then the screen result looks like the following.

 json demo controller test coding

Step 3: Now, replace the existing code in the file JsonDeomControllerTest.cs with the following code.

  1. using System;  
  2. using System.Web.Mvc;  
  3. using Microsoft.VisualStudio.TestTools.UnitTesting;  
  4. using JsonResultDemo.Controllers;  
  5.   
  6. namespace JsonResultDemo.Tests.Controllers  
  7. {  
  8.     [TestClass]  
  9.     public class JsonDemoControllerTest  
  10.     {  
  11.         [TestMethod]  
  12.         public void WelcomeNote()  
  13.         {  
  14.             JsonDemoController controller = new JsonDemoController();  
  15.   
  16.             JsonResult result = controller.WelcomeNote();  
  17.             string msg = Convert.ToString(result.Data);  
  18.             // Assert  
  19.             Assert.AreEqual("Welcome to the User", msg);  
  20.         }  
  21.     }  

Brief Note about TestMethod of WelcomeNote()

  • Create an object for JsonDemoController.

  • Save the result of JsonDemoController controller method “WelcomeNote” method result in the “result” parameter of the type JsonResult.

  • The string “msg” is assigned with the value from the Json Result (result.Data).

  • In this step, you are checking the expected output with the actual output using the Assert method. In a similar way the Assert Method provides other options like AreNotEqual, AreSame, IsNotNull and so on.
Step 4: Right-click on the WelcomeNote method and click on “Run Unit Tests” then the screen result looks like the following.



Step 5: You can also do the “Run Tests” by the clicking of (Ctrl +R, T). Then you can view the results in Test Explorer like the following.



Step 6: As you noticed in the Test Explorer screen shot it contains so many options like “Run All” and Run the selected/required options. You can try with those and will get an idea of it easily.



In a similar way, you can create more test methods and it will be helpful to check the functionality in various cases since it provides correct results or not.

Note: you can download the preceding discussed sample project from the link Source Code.

Conclusion

I hope this article gives you an idea of JsonResult, JsonResult Properties, the usage of JsonResult with various scenarios and how can you test the JsonResult using the Test Project.

Please provide your valuable suggestions and comments on this.