ASP.NET MVC에서 ActionName 특성(Attribute)은 액션 선택자(Action Selector) 중 하나로, 액션 메서드에 실제 메서드 이름과 다른 별칭 이름을 부여할 때 사용합니다. 즉, 메서드의 원래 이름 대신 다른 이름으로 해당 액션을 호출하고 싶을 때 이 특성을 활용할 수 있습니다.
[ActionName("AliasName")]컨트롤러(Controller) 예제
아래 예제는 Index 메서드에 "ListCountries"라는 별칭을 지정한 코드입니다.
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>
}
</ul>동작 방식
위 예제에서는 Index 메서드에 "ListCountries"라는 별칭 이름을 지정했습니다. 따라서 기존의 Index라는 액션 이름으로 접근하면 일치하는 액션을 찾지 못해 404 오류가 발생합니다.
반면, ListCountries라는 액션 이름으로 접근하면 정상적으로 국가 목록이 화면에 표시됩니다.