0

Say I have a controller action like so:

public ActionResult Foo() {
    return View(new SomeModel {...});
}

Is it possible for me to, at runtime, have this action return JSON instead of HTML? This is for some automated testing. The only way I have found would be to modify my controller's base class to override View(...) such that they if some setting is true, it returns Json(model) instead of what it normally does.

I'd rather not do that as it would mean a conditional which gets evaluated for every action even in non-test environments.

teo van kot
  • 12,350
  • 10
  • 38
  • 70
mamidon
  • 895
  • 1
  • 10
  • 25

2 Answers2

0

This is pretty trivial...

public ActionResult Foo() {
    var model = new SomeModel {...};

    if (somePropertyYouWantToCheck)
        return Json(model);

    return View(model);
}
Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
0

I found the MVC feature which does exactly what I want -- filters. In my case, a global result filter which replaces the ActionResult with a JsonResult.

See http://weblogs.asp.net/gunnarpeipman/asp-net-mvc-3-global-action-filters

mamidon
  • 895
  • 1
  • 10
  • 25