Reputation: 1110
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."
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
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