Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use case for using a JsonResult action in asp.net mvc3?

When is it typical to use the JsonResult action in an ASP.NET MVC 3 application?

From where is the JsonResult usually called; from another action or an actionlink rendered in the html?

Can you give me some examples where you want json instead of a typical view?

like image 537
Seth Spearman Avatar asked May 16 '12 19:05

Seth Spearman


People also ask

What is the use of JsonResult in MVC?

What is JsonResult ? JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).

What is the default case format of a JsonResult response in MVC in .NET C #?

The default content type for JSON is application/json; charset=utf-8.

What is the difference between ActionResult and JsonResult?

The ActionResult class Encapsulates the result of an action method and is used to perform a framework-level operation on behalf of the action method. And for JsonResult: Represents a class that is used to send JSON-formatted content to the response.

How do I return JSON from action method?

To return JSON (JavaScript Object Notation) content from controller, we use JsonResult return type in the action method of the controller.


3 Answers

Say, for example you wanted to populate a jQuery autocomplete with a list of values based on a selection of another field, so you can't determine the data on page load. I would typically call an action method in a $.ajax call, then return an array of items to populate the autocomplete with.

Example, here's my jQuery, one function for the call and another that gets called to populate the automcomplete with received data:

$(function() {
    $.ajax({
            url: '@Url.Action("GetHomes", "Account")',
            type: "POST",
            datatype: "json",
            success: function (data) {
                if (data.Success || data.Success == null) {
                    WireUpHomesData(data);
                } else {
                    ShowErrorDialog();
                }
            }
        });

    ShowDialog();
});

function WireUpHomesData(data) {
    var homes = new Array();

    for (var i = 0; i < data.length; i++) {
        homes[i] = { label: data[i].HomeName, text: data[i].HomeId, icon: data[i].HomeIcon, desc:data[i].HomeAddress };
    }
    $("#home").autocomplete({
            source: homes,
            select: function (event, item) {
                homeUrl = '@Url.Action("Site", "Sites")/' + item.item.text;
            }
        }).data("autocomplete")._renderItem = function (ul, item) {
        return $("<li></li>")
            .data("item.autocomplete", item)
            .append("<a><span class='" + item.icon + "'/><span class='fs-ui-autocomplete-home'>" + item.value + "</span><br>" + item.desc+ "</a>")
            .appendTo(ul);
    }; 
    $(".ui-autocomplete").addClass("fs-ui-autocomplete");
}

And here is my controller:

public JsonResult GetHomes()
{
    return Json(RequiresAclAttribute.HomesForUser());
}

And here's the method signature for the method that's called:

public IEnumerable<HomeInfo> HomesForUser()

And for clarity, here's the HomeInfo class:

public class HomeInfo
{
    public string HomeId { get; set; }
    public string HomeName { get; set; }
    public string DisplayName { get; set; }
    public string HomeAddress { get; set; }
    public string HomeIcon { get; set; }
}
like image 164
mattytommo Avatar answered Sep 22 '22 02:09

mattytommo


JsonResult is a subclass derived from ActionResult class. You can use this when you want to return a Json object.

public JsonResult GetItems()
{
  var jsonResult=new { Id = "23", Name = "Scott"};
  return Json(jsonResult,JsonBehaviour.AllowGet);
}

This will return the same result as

public ActionResult GetItems()
{
  var jsonResult=new { Id = "23", Name = "Scott"};
  return Json(jsonResult,JsonBehaviour.AllowGet);
}

Possible use of this is to get some chunk of data in asynchronous way. Ex : Imagine you have a drop down where you are showing the states and when user selects a state, you want to to bring the list of cities belongs to the state and show it in the page without a page refrest. you can call use jQuery ajax /getJson method (short hand of jQuery get with json as datatype) method to get this data from an ActionMethod which returns Json data.

A small example to call an Action method which returns the Json data

$(function(){
   $.getJSON('YourController/GetItems', function(data) {
      alert(data.Id);
      alert(data.Name );
   });
});

With JsonResult class the response content type will be "application/json" if nothing is specified explicitly. Internally The ExecuteResult method uses JavaScriptSerializer to Serialize the content when returning data.

like image 28
Shyju Avatar answered Sep 18 '22 02:09

Shyju


The JsonResult is very usefull wehn making ajax calls from javascript, e.g. using getJSON from jQuery: http://api.jquery.com/jQuery.getJSON/

The benefit of JsonResult is it returns a JSON formatted result without effort.

like image 27
Antonio Dlp Avatar answered Sep 21 '22 02:09

Antonio Dlp