Is there any attribute relating to AJAX to be set for ASP.NET MVC controller actions?

Saeed Neamati picture Saeed Neamati · Jul 2, 2011 · Viewed 19.5k times · Source

I want to use partial views with AJAX calls in ASP.NET MVC, and this is the first time I'm using it. I just searched to see if there is anything special I should know beforehand, and one of'em that I'm curious about, is to see if there is any special attribute that should be set or is related to AJAX calls? Something like [ChildActionOnly] or [HttpGet]

Answer

Muhammad Adeel Zahid picture Muhammad Adeel Zahid · Jul 2, 2011

I don't think there is built in attribute for ajax, but you can create your own AjaxOnly filter like this:

public class AjaxOnlyAttribute : ActionMethodSelectorAttribute 
{
    public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
    {
        return controllerContext.RequestContext.HttpContext.Request.IsAjaxRequest();
    }
}

And decorate your action methods like this:

[AjaxOnly]
public ActionResult AjaxMethod()
{
   
}

See Also: ASP.NET MVC Action Filter – Ajax Only Attribute for another way of implementing this