Is there any attribute relating to AJAX to be set for ASP.NET MVC controller actions?
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
ASP.NET MVC provides an extension method to check if an Request is an Ajax Request. You can use it to decide if you want to return a partial view or json result instead of a normal view.
if (Request.IsAjaxRequest())
{
return PartialView("name");
}
return View();
To limit an action method to Ajax calls only you can write a custom attribute. In case of a normal request this filter will return a 404 not found http exception.
[AttributeUsage(AttributeTargets.Method)]
public class AjaxOnlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 404;
filterContext.Result = new HttpNotFoundResult();
}
else
{
base.OnActionExecuting(filterContext);
}
}
}
you can use it like that:
[AjaxOnly]
public ActionResult Index() {
// do something awesome
}
A spinoff of Muhammad's answer letting you specify that it mustn't be an ajax request as well:
using System.Web.Mvc;
public class AjaxAttribute : ActionMethodSelectorAttribute
{
public bool ajax { get; set; }
public AjaxAttribute() { ajax = true; }
public AjaxAttribute(bool a) { ajax = a; }
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
return ajax == controllerContext.HttpContext.Request.IsAjaxRequest();
}
}
This lets you do things like...
[Ajax]
public PartialViewResult AjaxUpdatingPage() {
return PartialView();
}
[Ajax(false)]
public ViewResult NotAjaxUpdatingPage() {
return View();
}