Is there an ASP.NET MVC controller that can auto-handle JSON/XML/Views?
Is there an ASP.NET MVC controller or helper class tha开发者_如何学运维t can automatically return the proper HTTP response based on the HTTP request header? I'd like it to be able to return JSON, XML, or a View based on the request's content type, with the only thing I have to do is populate some global Model
object with data from the database.
Check out this article - you can do it using action filters:
The following is a filter which makes the whole thing much cleaner. The filter looks for Content-Type headers in the HTTP request. If it matches text/xml then Plain Old XML (POX) is returned and if it matches application/json the output is JSON.
Have a look at this article also, doesn't use filters and works great for me.
I use JSON responses in several places on my app, but if a users javascript is disabled it will fallback and render the standard view...it checks the response type to do this.
http://weblogs.asp.net/rashid/archive/2009/04/15/adaptive-rendering-in-asp-net-mvc.aspx
Paul
精彩评论