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.
Create a Custom Action Selector in ASP.NET MVC
Saturday, May 31, 2025
7 مشاهدة
Learn how to create and use custom action selectors in ASP.NET MVC to control action method selection based on custom logic
Create a Custom Action Selector
public class AjaxRequest: ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
return controllerContext.HttpContext.Request.IsAjaxRequest();
}
}
Apply Custom Action Selector
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:
[AjaxRequest()]
[HttpPost]
public ActionResult Edit(int id)
{
//write update code here..
return View();
}
Tags:
#tag1