Ticker

6/recent/ticker-posts

Action Selector Attributes in ASP.NET MVC

Action Selector Attributes in ASP.NET MVC

Introduction Action Selector Attributes in ASP.NET MVC are used to control the selection of actions in a controller based on various criteria. They provide a way to customize the routing and behavior of actions within an MVC application. In this documentation, we will explore some commonly used Action Selector Attributes and their usage.

Table of Contents

  1. [HttpGet]
  2. [HttpPost]
  3. [Route]
  4. [ActionName]
  5. [NonAction]

1. [HttpGet] The [HttpGet] attribute is used to specify that an action should only respond to HTTP GET requests. It restricts the action to be invoked only when the URL is accessed via the GET method. Below is an example:

csharp
[HttpGet] public ActionResult Index() { // Action code here return View(); }

2. [HttpPost] The [HttpPost] attribute is used to specify that an action should only respond to HTTP POST requests. It restricts the action to be invoked only when the URL is accessed via the POST method. Below is an example:

csharp
[HttpPost] public ActionResult Create(Product model) { // Action code here return RedirectToAction("Index"); }

3. [Route] The [Route] attribute is used to define a custom route for an action. It allows you to specify a URL pattern that will map to the action method. It provides more control over the routing behavior. Below is an example:

csharp
[Route("products/{id}")] public ActionResult Details(int id) { // Action code here return View(); }

4. [ActionName] The [ActionName] attribute is used to specify a custom action name for an action method. It allows you to use a different name for the action method than its actual method name. Below is an example:

csharp
[ActionName("Info")] public ActionResult Details(int id) { // Action code here return View(); }

5. [NonAction] The [NonAction] attribute is used to specify that a method should not be treated as an action method. It is useful when you have a method within a controller that should not be accessible as an action. Below is an example:

csharp
[NonAction] public void UtilityMethod() { // Method code here }

Conclusion Action Selector Attributes in ASP.NET MVC provide powerful tools for controlling the behavior and routing of actions within a controller. By using these attributes, you can fine-tune the accessibility, HTTP method restrictions, custom routing, and naming of your action methods, enhancing the flexibility and control of your MVC application.

Post a Comment

0 Comments