How can we provide an alias name for an action method in Asp .Net MVC C#?

CsharpServer Side ProgrammingProgramming

ActionName attribute is an action selector which is used for a different name of the action method. We use ActionName attribute when we want that action method to be called with a different name instead of the actual name of the method.

[ActionName("AliasName")]

Controller

Example

using System.Collections.Generic;
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      [ActionName("ListCountries")]
      public ViewResult Index(){
         ViewData["Countries"] = new List<string>{
            "India",
            "Malaysia",
            "Dubai",
            "USA",
            "UK"
         };
         return View();
      }
   }
}

View

@{
   ViewBag.Title = "Countries List";
}
<h2>Countries List</h2>
<ul>
@foreach(string country in (List<string>)ViewData["Countries"])
{
   <li>@country</li>
}

In the above since we have provided a different action name for the Index method, when we try to navigate with action name Index will get 404 error.

Now let us try to navigate using ListCountries action name.


raja
Published on 24-Sep-2020 16:00:16
Advertisements