Back

How to define a custom action selector in ASP.NET MVC?


Action selectors are attributes that can be applied to action methods. The MVC framework uses Action Selector attribute to invoke correct action.

You can create custom action selectors by implementing the ActionMethodSelectorAttribute abstract class.

For example, create custom action selector attribute AjaxRequest to indicate that the action method will only be invoked using the Ajax request as shown below.

Example: Create a Custom Action Selector
public class AjaxRequest: ActionMethodSelectorAttribute
{
    public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
    {
        return controllerContext.HttpContext.Request.IsAjaxRequest();
    }
} 

In the above code, we have created the new AjaxRequest class deriving from ActionMethodSelectorAttribute and overridden the IsValidForRequest() method.

So now, we can apply AjaxRequest attributes to any action method which handles the Ajax request, as shown below:

Example: Apply Custom Action Selector
[AjaxRequest()]
[HttpPost]
public ActionResult Edit(int id)
{
    //write update code here..

    return View();
}

Thus, you can create custom action selector attributes for your requirements.