ASP.NET MVC: Would it be good practice to have an API Controller action return both View and/or JSON ASP.NET MVC: Would it be good practice to have an API Controller action return both View and/or JSON json json

ASP.NET MVC: Would it be good practice to have an API Controller action return both View and/or JSON


If your view's model is suitable for returning as JSON too, doing both in the same action can work well. Something like:

public ActionResult Foo(){  FooModel model = new FooModel();  // Code here to build the model  if (Request.IsAjaxRequest())    return Json(model);  else    return View(model);}

This also helps guide you into the pit of success in terms of using progressive enhancement. If the URL for HTML and JSON is the same, it's that much easier to use accessible/SEO-friendly URLs in your markup and then progressively enhance by adding unobtrusive event handlers to replace that with requests for the JSON in JavaScript-enabled browsers.


I've seen one action method return both before, but, in my opinion, you are better off having two separate action methods. You can have them both call off to another method with the shared code, but since they are used for two very different things, you might find it is easier to maintain if you have two methods (a future requirement might cause one to change in a way that makes it difficult to support both in a single method).

Whether they are in the same controller or not is really more dependent on the nature, size, and complexity of the application. I have separated the API as a completely different project from the HTML. I have shared dlls for accessing the data and other common functions, but the MVC projects are different.


Depending what you exactly want to achieve: