Sunday, May 12, 2013

Returning Json Results from Mvc Controllers without JsonResult

Some of the developers may not like returning JsonResult, because it may hide the actual data type we intend to return. They may like to return an object which should be automatically converted to JSON by the controller. The default ASP.NET controller will not do this. We have a work around to fix this.


Action invocation in ASP.NET MVC controller is accomplished by ActionInvoker. IActionInvoker is the base interface used by ASP.NET MVC controller for Action invocation. System.Web.Mvc.Async.AsyncControllerActionInvoker  is one of the default action invoker for ASP.NET MVC. We can change the default Action Invoker of a Controller by changing the ActionInvoker property of a controller. Before that we may have to created our own Action invoker for converted object to JsonResult.


public class JsonControllerActionInvoker : AsyncControllerActionInvoker {
    protected override ActionResult CreateActionResult(
        ControllerContext controllerContext,
        ActionDescriptor actionDescriptor,
        object actionReturnValue) {


       return actionReturnValue == null
            ? new EmptyResult()
            : (actionReturnValue as ActionResult)
            ?? new JsonResult() { Data = actionReturnValue, JsonRequestBehavior = JsonRequestBehavior.AllowGet };


Then we can change the controller’s Action invoker in the controller’s constructor, with the following code.

this.ActionInvoker = new JsonControllerActionInvoker();


Instead of adding this code to all our controller class we can have a base controller for this.


public class JsonController : Controller {
    public JsonController() {
        this.ActionInvoker = new JsonControllerActionInvoker();

No comments:

Post a Comment