Menu

Tuesday, 28 October 2014

ContentResult in MVC

About

ContentResult is one of the ActionResult type in MVC. This is mostly used to display dynamic content to the user based on various conditions. So, you can return various types of content like plain text, xml, html etc.

In this article you are going to learn about the following things.
  1. ContentResult and its properties
    • Content
    • ContentType
    • ContentEncoding
  1. Return various Types of Content
    • Plain Text
    • Html
    • XML
ContentResult and its Properties

Content: Its used to send the content data in a string format.

ContentType: It helps to indicate the content type. The default content type for ContentResult is text/html; charset=utf-8.

ContentEncoding: It helps to indicate the content encoding type, the default encoding  type  for ContentResult  is UTF-8.
Return Various Types of Content

In this scenario, you will get a more idea by creating sample application with the following these steps.

Step 1:
Create a new project with the name ContentResultDemo and choose the template as Empty as shown in the following screen shots.



Now, click on Ok button then the screen would display like the below.



Step 2:
After clicking on Ok button the project would be created.  Then create a controller named as “ContentDemoController” like the below.


Now, click on "Controller" then the displayed screen is as follows.



Click on "Add"  button then the output template window is as follows.



Enter the name as "ContentDemoController" as mentioned in the aforesaid screenshot and then click on "Add" button then controller would be created and its displayed like the below.



Step 3:
Now, Replace the default code in the ContentDemoController.cs file with the following code.

using System.Web.Mvc;

namespace ContentResultDemo.Controllers
{
    public class ContentDemoController : Controller
    {
        // GET: ContentDemo
        public ActionResult Index()
        {
            return Content("test content");
        }
    }
}

And then Build the application (hit F6) and run the application (hit F5) then navigate to the following Url (http://localhost:50589/ContentDemo/)

Note: The port address in the above Url might be a chance to changed at your end.

The output screen looks like below.



Till now, you have created one Index action method with sample test content in the ContentDemoController.cs  file.

Step 4:

Add the following code in ContentDemo controller class file which helps to return sample content based on its content type.

        /// 
        /// Returns sample content based on its content type
        /// 
        /// content type
        /// As String
        public string SampleContent(int contentType)
        {
            switch (contentType)
            {
                case (int)ContentTypes.PlainText:
                    return "Plain Text";
                case (int)ContentTypes.Html:
                    return "
Name
Ramchand
Test
"; case (int)ContentTypes.Xml: return "" + "Ramchand" + "Srinivas" + ""; default: return string.Empty; } } /// /// Content Types enum /// public enum ContentTypes { PlainText = 1, Html, Xml }


Plain Text:

To display the plain text by using ContentResult as return type, you have to add the below action method.


        /// 
        /// Returns Plain Content
        /// 
        /// 
        public ActionResult PlainContent()
        {
            return Content(SampleContent((int)ContentTypes.PlainText), 
                        "text/plain");
        }

Now, run the application (hit F5) and navigate to this Url (http://localhost:50589/ContentDemo/PlainContent) then the displayed output is like the below.



Html:

To display the Html output, add the following action controller method with this code

        /// 
        /// Returns Html Content
        /// 
        /// 
        public ActionResult HtmlContent()
        {
            return Content(SampleContent((int)ContentTypes.Html), 
                        "text/html");
        }

Now, run the application (hit F5) and navigate to this Url (http://localhost:50589/ContentDemo/HtmlContent) then the displayed output is like the below.



Xml:

To display the Xml output, add the below action method in the ContenDemoController.cs file

        /// 
        /// Returns Xml Content
        /// 
        /// 
        public ActionResult XmlContent()
        {
            return Content(SampleContent((int)ContentTypes.Xml), 
                        "application/xml");
        }

Now, run the application (hit F5) and navigate to this Url (http://localhost:50589/ContentDemo/XmlContent) then the displayed output is like the below.



As, you have observed in the above examples, the Content property for Content Result is only string. Even though while displaying at browser it would changes based on the content type which you have specified in the Content Result.

The whole code you have implemented in the ContentDemoController.cs file is as follows.

using System.Web.Mvc;

namespace ContentResultDemo.Controllers
{
    public class ContentDemoController : Controller
    {
        // GET: ContentDemo
        public ActionResult Index()
        {
            return Content("test content");
        }

        /// 
        /// Returns Plain Content
        /// 
        /// 
        public ActionResult PlainContent()
        {
            return Content(SampleContent((int)ContentTypes.PlainText), 
                        "text/plain");
        }

        /// 
        /// Returns Html Content
        /// 
        /// 
        public ActionResult HtmlContent()
        {
            return Content(SampleContent((int)ContentTypes.Html),
                        "text/html");
        }

        /// 
        /// Returns Xml Content
        /// 
        /// 
        public ActionResult XmlContent()
        {
            return Content(SampleContent((int)ContentTypes.Xml), 
                        "application/xml");
        }

        /// 
        /// Returns sample content based on its content type
        /// 
        /// content type
        /// As String
        public string SampleContent(int contentType)
        {
            switch (contentType)
            {
                case (int)ContentTypes.PlainText:
                    return "Plain Text";
                case (int)ContentTypes.Html:
                    return "
Name
Ramchand
Test
"; case (int)ContentTypes.Xml: return "" + "Ramchand" + "Srinivas" + ""; default: return string.Empty; } } /// /// Content Types enum /// public enum ContentTypes { PlainText = 1, Html, Xml } } }

Conclusion
 
I hope you got an idea about ContentResult and its properties and how can you send various types of content by just changing the ContentType property in ContentResult. Please provide your suggestions and comments if any.

Wednesday, 22 October 2014

JsonResult Type in MVC

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.



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



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.



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



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



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.




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



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.

using System;  
using System.Collections.Generic;  
using System.Text;  
using System.Web.Mvc;  
using System.Web.Script.Serialization;  
using JsonResultDemo.Models;  
  
namespace JsonResultDemo.Controllers  
{  
    public class JsonDemoController : Controller  
    {  
        #region ActionControllers  
  
        ///   
        /// Welcome Note Message  
        ///   
        /// In a Json Format  
        public JsonResult WelcomeNote()  
        {  
            bool isAdmin = false;  
            //TODO: Check the user if it is admin or normal user, 
            //(true-Admin, false- Normal user)  
            string output = isAdmin ? "Welcome to the Admin User" 
                            : "Welcome to the User";  
  
            return Json(output, JsonRequestBehavior.AllowGet);  
        }  
     }  
}  

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.



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.



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



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.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
  
namespace JsonResultDemo.Models  
{  
    public class UserModel  
    {  
        public int UserId { get; set; }  
        public string UserName { get; set; }  
        public string Company { get; set; }  
    }  
}  

Step 3: Add one method named GetUsers in the JsonDemoController.cs file that will return the list of sample users.  

        
        ///   
        /// Get the Users  
        ///   
        ///   
        private List GetUsers()  
        {  
            var usersList = new List  
            {  
                new UserModel  
                {  
                    UserId = 1,  
                    UserName = "Ram",  
                    Company = "Mindfire Solutions"  
                },  
                new UserModel  
                {  
                    UserId = 1,  
                    UserName = "chand",  
                    Company = "Mindfire Solutions"  
                },  
                new UserModel  
                {  
                    UserId = 1,  
                    UserName = "Abc",  
                    Company = "Abc Solutions"  
                }  
            };  
  
            return usersList;  
        }

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

///   
/// Get tthe Users data in Json Format  
///   
///   
public JsonResult GetUsersData()  
{  
    var users = GetUsers();  
    return Json(users, JsonRequestBehavior.AllowGet);  
}  

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



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.

///   
/// Sample View  
///   
///   
public ActionResult Sample()  
{  
    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.



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.



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.

@{  
    Layout = null;  
} 
  
  
      
          
        Create Sample JSON Data and send it to controller  
      
      
        

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.

///   
/// Update the user details  
///   
/// users list in JSON Format  
///   
[HttpPost]  
public JsonResult UpdateUsersDetail(string usersJson)  
{  
    var js = new JavaScriptSerializer();  
    UserModel[] user = js.Deserialize(usersJson);  
  
    //TODO: user now contains the details, you can do required operations  
    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.



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.



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.

///   
/// Get the huge list of users  
///   
///   
private List GetUsersHugeData()  
{  
 var usersList = new List();  
 UserModel user;  
 for (int i = 1; i < 51000; i++)  
 {  
  user = new UserModel  
  {  
   UserId = i,  
   UserName = "User-"+i,  
   Company = "Company-"+i  
  };  
  usersList.Add(user);  
 }  

 return usersList;  
} 

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

    ///   
    /// Get the huge list of Users  
    ///   
    ///   
    public JsonResult GetUsersHugeList()  
    {  
        var users = GetUsersHugeData();  
        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.



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.

///   
/// Override the JSON Result with Max integer JSON lenght  
///   
/// Data  
/// Content Type  
/// Content Encoding  
/// Behavior  
/// As JsonResult  
protected override JsonResult Json(object data, string contentType,  
    Encoding contentEncoding, JsonRequestBehavior behavior)  
{  
    return new JsonResult()  
    {  
        Data = data,  
        ContentType = contentType,  
        ContentEncoding = contentEncoding,  
        JsonRequestBehavior = behavior,  
        MaxJsonLength = Int32.MaxValue  
    };  
}

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.



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


using System;  
using System.Collections.Generic;  
using System.Text;  
using System.Web.Mvc;  
using System.Web.Script.Serialization;  
using JsonResultDemo.Models;  
  
namespace JsonResultDemo.Controllers  
{  
    public class JsonDemoController : Controller  
    {  
        #region ActionControllers  
  
        ///   
        /// Welcome Note Message  
        ///   
        /// In a JSON Format  
        public JsonResult WelcomeNote()  
        {  
            bool isAdmin = false;  
            //TODO: Check the user if it is admin or normal user, (true-Admin, false- Normal user)  
            string output = isAdmin ? "Welcome to the Admin User" : "Welcome to the User";  
  
            return Json(output, JsonRequestBehavior.AllowGet);  
        }  
  
        ///   
        /// Get tthe Users data in JSON Format  
        ///   
        ///   
        public JsonResult GetUsersData()  
        {  
            var users = GetUsers();  
            return Json(users, JsonRequestBehavior.AllowGet);  
        }  
  
        ///   
        /// Sample View  
        ///   
        ///   
        public ActionResult Sample()  
        {  
            return View();  
        }  
  
        ///   
        /// Update the user details  
        ///   
        /// users list in JSON Format  
        ///   
        [HttpPost]  
        public JsonResult UpdateUsersDetail(string usersJson)  
        {  
            var js = new JavaScriptSerializer();  
            UserModel[] user = js.Deserialize(usersJson);  
  
            //TODO: user now contains the details, you can do required operations  
            return Json("User Details are updated");  
        }  
          
        ///   
        /// Get the huge list of Users  
        ///   
        ///   
        public JsonResult GetUsersHugeList()  
        {  
            var users = GetUsersHugeData();  
            return Json(users, JsonRequestBehavior.AllowGet);  
        }  
 
        #endregion  
 
 
        #region Methods  
  
        ///   
        /// Get the Users  
        ///   
        ///   
        private List GetUsers()  
        {  
            var usersList = new List  
            {  
                new UserModel  
                {  
                    UserId = 1,  
                    UserName = "Ram",  
                    Company = "Mindfire Solutions"  
                },  
                new UserModel  
                {  
                    UserId = 1,  
                    UserName = "chand",  
                    Company = "Mindfire Solutions"  
                },  
                new UserModel  
                {  
                    UserId = 1,  
                    UserName = "Abc",  
                    Company = "Abc Solutions"  
                }  
            };  
  
            return usersList;  
        }  
  
        ///   
        /// Get the huge list of users  
        ///   
        ///   
        private List GetUsersHugeData()  
        {  
            var usersList = new List();  
            UserModel user;  
            for (int i = 1; i < 51000; i++)  
            {  
                user = new UserModel  
                {  
                    UserId = i,  
                    UserName = "User-"+i,  
                    Company = "Company-"+i  
                };  
                usersList.Add(user);  
            }  
  
            return usersList;  
        }  
  
        ///   
        /// Override the Json Result with Max integer JSON lenght  
        ///   
        /// Data  
        /// Content Type  
        /// Content Encoding  
        /// Behavior  
        /// As JsonResult  
        protected override JsonResult Json(object data, string contentType,  
            Encoding contentEncoding, JsonRequestBehavior behavior)  
        {  
            return new JsonResult()  
            {  
                Data = data,  
                ContentType = contentType,  
                ContentEncoding = contentEncoding,  
                JsonRequestBehavior = behavior,  
                MaxJsonLength = Int32.MaxValue  
            };  
        }  
 
        #endregion  
    }  
}

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.



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



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



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

using System;  
using System.Web.Mvc;  
using Microsoft.VisualStudio.TestTools.UnitTesting;  
using JsonResultDemo.Controllers;  
  
namespace JsonResultDemo.Tests.Controllers  
{  
    [TestClass]  
    public class JsonDemoControllerTest  
    {  
        [TestMethod]  
        public void WelcomeNote()  
        {  
            JsonDemoController controller = new JsonDemoController();  
  
            JsonResult result = controller.WelcomeNote();  
            string msg = Convert.ToString(result.Data);  
            // Assert  
            Assert.AreEqual("Welcome to the User", msg);  
        }  
    }  
}  

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.