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

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

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

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

Example: Create 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 new AjaxRequest class deriving from ActionMethodSelectorAttribute and override a method named IsValidForRequest() method.

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

Example: Apply Custom Acton Selector
public ActionResult Edit(int id)
    //write update code here..

    return View();

Thus, you can create custom action selectors attributes for your requirement.