views:

26

answers:

1

Hi guys,

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  A: 

Why not just return a JSonResult?

public ActionResult MyAction()
{
    return Json( new Product { Name = "Foo", ID = 1 } );
}
tvanfosson
I want avoid ActionResult as return parameter.I want my method be declared as: public Product MyAction()Is it possible in MVC?
Alexey Zakharov
You could try overriding ToString() on the project class so that it return the object formatted as JSON, but you'd probably have to change the ContentType on the Response manually in your method each time as otherwise it will use the default -- decidedly not `application/json`. Why are you so keen to have the method return a `Product` instead of an `ActionResult`? It not that hard to unpack the JSON result for unit testing.
tvanfosson