0

With ASP.NET MVC 5, you can skip the ugly "ActionResult" return type, and instead, specify a 'real' class. However, it seems that MVC wants to return the .ToString() version of my object as Content instead of the JSON serialized version of my object that I want - similar to ASP.NET MVC WebApi2.

Given this controller... how do I get a JSON result without changing the method at all?

public class MyController : Controller
{
    public Thing GetSomething()
    {
        return new Thing { Name = "Justin_Example" };
    }
}
Timothy Khouri
  • 31,315
  • 21
  • 88
  • 128
  • You can probably do that in an action filter. – SLaks Jan 26 '15 at 22:26
  • Wait, do you mean MVC6 or MVC5? MVC5 doesn't support this as far as I know, returning something like that is the same as `return Content(...);` If you believe it should work, can you provide a reference that supports this usage? MVC6 has POCO controllers, which may be what you're referring to. – Erik Funkenbusch Jan 26 '15 at 22:33
  • Yes MVC5 (hence the tag), and I can't believe that the ability to return a complex object meant that `.ToString()` is the goal - that would be the worst feature ever :) – Timothy Khouri Jan 27 '15 at 12:58
  • I suspect that the problem here is that you're returning, in your controller, a class of your own whose your environment doesn't know how to process. So it apply some "default" behaviour. Maybe if you serialize your object and return the string you'll be able to send it. – Bardo Jan 27 '15 at 14:00

1 Answers1

0

I am not sure if it is what you need but you can set return type as JsonResult. Here is an example:

public JsonResult GetSomething()
{
    var thing = new Thing { Name = "Justin_Example" };
    return Json(thing , JsonRequestBehavior.AllowGet);
}
Mateusz Cisek
  • 775
  • 11
  • 22
  • Thanks for the post - what I'm looking for though is to *not* explicitly say `JsonResult` and then use the Json method - but rather, proper types. Think in terms of Unit Testing (though that is not my motive) – Timothy Khouri Jan 27 '15 at 13:58