Bjorn
Bjorn

Reputation: 1110

Unified MVC and Web Api - same controller for views and json?

One of the new features in visual studio 2015 (preview) is that "ASP.NET MVC and Web API... have been unified into a single programming model."

http://blogs.msdn.com/b/webdev/archive/2014/11/12/announcing-asp-net-features-in-visual-studio-2015-preview-and-vs2013-update-4.aspx

I assumed that this meant that I could write a single controller action "GetCustomerById", that returned a Customer object and that it could be rendered either as serialized Json or as Html (using an mvc view) based on content negotiation. (if the user requested it with "Accept: application/json" or "Accept: text/html")

But I cannot see how this can be done, they still seem to require different controller and methods?

Upvotes: 7

Views: 1553

Answers (1)

Jay
Jay

Reputation: 886

This can be done without the new unified model. In any MVC controller you can inspect the headers as well as the Request.IsAjaxRequest() method to determine whether how to return data.

Here is bare-bones simplified example of such a method:

internal ActionResult ReturnResultAsRequested(object result)
{
  if (Request.Headers["Accept"].Contains("application/json"))
    return Json(result);
  else if (Request.IsAjaxRequest())
    return PartialView(Request.RequestContext.RouteData.Values["Action"], result);
  else
    return View(Request.RequestContext.RouteData.Values["Action"], result);
}

Upvotes: 3

Related Questions