Action selectors in MVC

Action selectors in ASP.NET MVC

Actions are public methods in an MVC controller that responds to an URL request. Action Selectors are attributes that can be applied to action methods and are used to influence or control which action method gets invoked in response to a request. It helps the routing engine to select the correct action method to handle a particular request.

MVC 5 includes the following action selector attributes:

  1. ActionName
  2. ActionVerbs
  3. NonAction
To understand these Action Selectors let’s create an empty MVC application.

Open Visual Studio and create a new project

Select File => New => Project

Action Selectors in ASP.NET MVC

After clicking on “Project” link a new dialog will pop up.

In that we are going to select web templates from the left pane after selecting web template, we need to select the web template as “ASP.NET Web Application” as shown below.

Action Selectors in ASP.NET MVC

After selecting this project template next we are going to name the project as “ActionSelectorsinMVC” and clicking on the OK button a new dialog will pop up with Name “New ASP.NET Project” for selecting project Templates.

Action Selectors in ASP.NET MVC

In this dialog, we are going to choose MVC project template and then we are going to choose Authentication type for doing that just click on Change Authentication button, a new dialog will pop up with the name “Change Authentication” here we are going to choose No Authentication click on OK Button.

It will take some to time create the project for us. Once the project is created let’s see the folder structure as shown below

Action Selectors in ASP.NET MVC

Next, we need to add our model class in the Models folder.

Right click on the Models folder and click on Add => Class and give the class name as Product.cs

Then copy and paste the following code in Product.cs class file

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public int Price { get; set; }
    public string Category { get; set; }
}

public class DataAccessElectronics
{
    public List<Product> GetDataElectronics()
    {
        List<Product> ElectronicsProductList = new List<Product>()
            {
                new Product() { ProductId = 1, ProductName = "Desktop", Price = 34000, Category = "Electronics" },
                new Product() { ProductId = 2, ProductName = "Laptop", Price = 34000, Category = "Electronics" },
                new Product() { ProductId = 3, ProductName = "Router", Price = 34000, Category = "Electronics" },
                new Product() { ProductId = 4, ProductName = "Mouse", Price = 34000, Category = "Electronics" },
                new Product() { ProductId = 5, ProductName = "USB HDD", Price = 34000, Category = "Electronics" },
                new Product() { ProductId = 6, ProductName = "LCD", Price = 34000, Category = "Electronics" }
            };

        return ElectronicsProductList;
    }
}

The above code contains following classes

Product – This is an entity class containing properties for Product information.

DataAccessElectronics – This class contains the method for returning all Electronics products.

Note: In a real-world example, Entity framework can be used here to map with the database server.

In this article, I will discuss action selectors in asp.net MVC 

The ActionName action selector is used when we want to invoke an action method with a different name, then what is already given to the action method. 

Let’s modify the HomeController as shown below
public class HomeController : Controller
{
    public string Index()
    {
        return "Index action method invoked";
    }
}

The following URL request would invoke Index() action method in HomeController

/Home/Index
If you want to invoke Index() action method, with the following URL

/Home/List
Then decorate the action method with the ActionName attribute as shown below.

public class HomeController : Controller
{
    [ActionName("List")]
    public string Index()
    {
        return "Index action method invoked";
    }
}

Now, if you navigate to /Home/Index, you will get an error – The resource cannot be found as shown below.

Action Selectors in ASP.NET MVC

At the moment, the Index() action method is returning a string, but if it returns a view, should the view be named – Index or List.?

The list should be the view name.

Let’s modify the Home Controller as shown below.
public class HomeController : Controller
{
    [ActionName("List")]
    public ActionResult Index()
    {
        DataAccessElectronics DAE = new DataAccessElectronics();
        List<Product> ElectronicsList = DAE.GetDataElectronics();
        return View(ElectronicsList);
    }
}

Let’s add two views with the name List.cshtml and Index.cshtml within the Home folder and copy and paste the following code in both the views.

@model IEnumerable<ActionSelectorsinMVC.Models.Product>

@{
    ViewBag.Title = "Index";
}

<h2>Product List</h2>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.ProductName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Category)
        </th>
        
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.ProductName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Price)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Category)
        </td>
    </tr>
}

</table>

Run the application and navigate to Home/List it will display the following output as the response.

Action Selectors in ASP.NET MVC

Now for some reason, if we want to use “Index” as the view name then modify the controller action method as shown below.

public class HomeController : Controller
{
    [ActionName("List")]
    public ActionResult Index()
    {
        DataAccessElectronics DAE = new DataAccessElectronics();
        List<Product> ElectronicsList = DAE.GetDataElectronics();
        return View("Index", ElectronicsList);
    }
}

Now run the application and navigate to Home/List it will display the same out.

SUMMARY

In this article, I try to explain Action Selectors in ASP.NET MVC application step by step with some simple example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *