I've been unable to find a concrete answer regarding this question. I've viewed posts and subsequent posts from this question and elsewhere but all I've really come out of reading is that JsonResult has a hardcoded content type and there really isn't any performance gains.
If both results can return Json why would you need to use JsonResult over ActionResult.
public ActionResult()
{
return Json(foo)
}
public JsonResult()
{
return Json(bar)
}
Can anyone explain a scenario where ActionResult simply can't get the job done and JsonResult must be used. If not, why does JsonResult exist in the first place.
Best Answer
I usually return concrete results (e.g.
JsonResult
,ViewResult
) and there are my pros:PartialViewResult
andViewResult
as result type precisely.There are some links where people support this approach:
There is a quote from Pro ASP.NET MVC 3 Framework:
I would use
ActionResult
over concrete one only if an action should return different types of results. But it is not that common situation.I'd like also to add that
ActionResult
is an abstract class so you cannot simply create an instance of this type and return it.JsonResult
is concrete so you can create its instance and return from an action method. There are many other types that derived fromActionResult
and basically all of them are used to overrideExecuteResult
method.This method is invoked by
ControllerActionInvoker
and implements logic writing data toresponse
object.ControllerActionInvoker
does not know about concrete results so that it can handle any result that is derived fromActionResult
and implementsExecuteResult
.In both cases you return an instance of
JsonResult
type in your example andJson(model)
it is simply a Factory Method that creates an instance ofJsonResult
.There is another SO question Is it better to have a method's datatype be as specific as possible or more general? where best practices for method parameters and return values are discussed.
The general idea is providing abstract types as parameters so that your method can handle wider range of parameter; returning concrete enough types so that your clients do not need to cast or convert them.