2
votes

By default ASP.NET MVC uses ContentResult for controller method that return result not inherited from actionresult type. That is why if we will return some poco entity it will be only its type name.

Could I overload something in controller to make it return jsonresult by default.

Example:

// return json product representation instead of product typename

public MyController: Controller
{
    public Product MyAction()
    {
          return new Product { Name = "Foo", ID = 1 };
     }
}

Best regards, Alexey Z.

2

2 Answers

3
votes

Why not just return a JSonResult?

public ActionResult MyAction()
{
    return Json( new Product { Name = "Foo", ID = 1 } );
}
1
votes

You can decorate your controller with an attribute like this one:

public class ReturnJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var result = filterContext.ActionDescriptor.Execute(filterContext, filterContext.ActionParameters);
        filterContext.Result = new JsonResult {Data = result};
    }
}