Yesterday I mentioned that one should download ASP.NET MVC Futures to get a few extra goodies to help one with their ASP.NET MVC Web Applications:
In addition to using Html.RenderAction, I also just used another item in the ASP.NET MVC Futures, called AcceptAjaxAttribute.
AcceptAjaxAttribute is an ActionMethodSelectorAttribute that specifically says an action responds to an Ajax Request and only an Ajax Request. So if you have an action method on your controller and only want the action to respond to AJAX Requests from jQuery, ASP.NET AJAX, etc., you can decorate the public method ( action ) on your controller with the AcceptAjaxAttribute:
[AcceptAjaxAttribute]
public ActionResult FetchHotels()
{
// ...
}
This isn't rocket science, because as you would expect it is just interrogating Request.IsAjaxRequest() to check if the request is coming from jQuery or another AJAX Framework. Here is the IsValidForRequest Method implemented by the AcceptAjaxAttribute:
public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
return controllerContext.HttpContext.Request.IsAjaxRequest();
}
The nice thing about using the AcceptAjaxAttribute over using IsAjaxRequest directly in your controller actions is that you don't have to deal with throwing a 404 HttpException within your action if it is not an Ajax Request. Hence, use the AcceptAjaxAttribute for those Ajax Only Actions in the ASP.NET MVC Framework.
ASP.NET MVC Tutorials