JSON Result JavaScript Result File Result Content Result Empty Result in MVC

JSON Result JavaScript Result File Result Content Result Empty Result  in MVC

In this article, I am going to discuss the JSON Result JavaScript Result File Result Content Result Empty Result in MVC application. 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 view page for the given request. 

Please read the following two articles before proceeding to this article.

Action Result Overview in ASP.NET MVC

View Result and Partial View Result in ASP.NET MVC.

We are going to work with the same example that we started in View Result and Partial View Result in ASP.NET MVC article,

File Result

The File Result returns different type of file format view when we implement the file download concept in MVC using file result. Let us understand File Result with an example. Please modify the HomeController as shown below.

public class HomeController : Controller
{
    public FileResult Index()
    {
        return File("Web.Config", "text");
    }
}

If you want to return a file from your action method then you need to use this File Result as the return type of your action method. Moreover, depending on the overload version of the File you use, you can specify what action the browser is going to take with the downloaded file.

For example, if you just specify a URL and a MIME (Multipurpose Internet Mail Extensions) type, then the browser attempts to display the file specified (the supported browsers are Firefox, Chrome, and IE10).

Let’s create a Folder called “Files” and a text file to this folder with the name “SimpleText.txt” as shown below.

JSON Result JavaScript Result File Result Content Result Empty Result in MVC application

Within the SimpleText.txt file write down the following

This is a Text file

Next, modify the Home Controller to use File Result as shown below
public class HomeController : Controller
{
    public FileResult Index()
    {
        return File(Url.Content("~/Files/SimpleText.txt"), "text/plain");
    }
}

We can also just return the byte array for the file content, which (in Chrome at least) will display the file in the browser:

public class HomeController : Controller
{
    public FileResult Index()
    {
        byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath("~/Files/SimpleText.txt"));
        return File(fileBytes, "text/plain");
    }
}

Another overload will specify a download name, and using this overload causes the browser to download the file, rather than just display it:

public class HomeController : Controller
{
    public FileResult Index()
    {
        return File(Url.Content("~/Files/SimpleText.txt"), "text/plain", "testFile.txt");
    }
}

The FileResult in MVC is one of the most open-ended ActionResults and can handle a lot of different scenarios. It can accept byte arrays, FileStreams, and URLs of files and in all scenarios return or download the file specified.

Content Result

The Content Result in ASP.NET MVC returns different content format to the view like HTML format, JavaScript format, and any other format.

We need to use the ContentResult in MVC when we want to allow the action to specify what should be returned. It’s a sort of catch-all for scenarios where we need to allow the action full control over the returned content. All we need to do is specify the content and MIME type:

Let us modify the HomeController as shown below to use Content Result in MVC.

public class HomeController : Controller
{
    public ContentResult Index()
    {
        return Content("<h3>Here's a custom content header</h3>", "text/html");
    }
}

Calling this action will display the h3 tag in the browser.

But the most interesting thing about ContentResult is that if you do this:

public class HomeController : Controller
{
    public string Index()
    {
        return "<h3>Here's a custom content header</h3>";
    }
}

MVC actually creates a ContentResult and wraps it around the returned value and it doesn’t have to be a string. But if we return null, in that case, MVC returns an EmptyResult.

Empty Result

MVC wants us to use EmptyResult when the action is specifically intended to return nothing. Unlike all of the previous ActionResults though, EmptyResult doesn’t have a helper. Additionally, if an action returns null, MVC will detect that and make it return an EmptyResult.

Let’s Modify the Home Controller to use Empty Result as shown below

public class HomeController : Controller
{
    public EmptyResult Empty()
    {
        return new EmptyResult();
    }

    public ActionResult NothingReturned()
    {
        return null; //Returns an EmptyResult
    }
}
JSON Result

The JSON result is one of the most important Action Result in ASP.NET MVC application. This action result returns the data in JSON Format i.e. in the 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) });
    }
}

Output:

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

Problems with JSON dates aside, the implications of this are staggering. Since that just encoded an anonymous object, it follows that JsonResult can handle any object, including user-defined ones, and encode them into the JSON format.

However, there’s one trick we should be aware of. If we attempt to redirect to the action above, MVC will throw an exception saying that “This 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 browsers to access this 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.

Json with Complex Type:

Create a Model as shown below

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

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, 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 maximum length. Assign the maximum length of data Using “MaxJsonLength” property.

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, JsonRequestBehavior.AllowGet);
        jsonResult.MaxJsonLength = int.MaxValue;
        return jsonResult;
    }
}

JavaScript Result

Another potentially dangerous ActionResult is the JavaScriptResult, which returns a script that is to be executed by the browser.

Step 1: Add this JavaScriptResult() method in home controller.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public JavaScriptResult WarningMessage()
    {
        var msg = "alert('Are you sure want to Continue?');";
        return new JavaScriptResult() { Script = msg };
    }
}

Step 2: Open Index.cshtml and add the following code.

@{
    ViewBag.Title = "DOT NET TUTORIALS";
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<div class="jumbotron">
    <h2 style="color:chocolate">Welcome to Learn MS</h2>
</div>

<script>
    $(document).ready(function () {
        $("button").click(function () {
            $.getScript("/Home/WarningMessage");
        });
    });
</script>

<button>Show Message</button>

When we click on Show Message button it will display the page as shown below

JSON Result JavaScript Result File Result Content Result Empty Result in MVC application

This can be really useful for MVVM scenarios and other dynamic script scenarios, but be cautious about using it, as it potentially violates the separation of concerns by making the Controller in charge of View functionality.

In the next article, I will discuss RedirectResult, RedirectToRoute, and RedirectToAction Results in ASP.NET MVC.

SUMMARY

In this article, I try to explain JSON Result JavaScript Result File Result Content Result Empty Result in ASP.NET MVC application step by step with a simple example. 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. Required fields are marked *