Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 ActionName attribute, its behaviour and effects

While reading about mcv3 I came across an attribute name called [ActionName]. It actually gives a new name to the action method. I tested a scenario which made me think; how are the internals working. When I have the following two action methods in my controller class

[ActionName("Test")]
public ActionResult Index()
{
      return View();
}
[ActionName("Index")]
public ActionResult Test()
{
      return View();
}

I thought this will end up in some kind of infinite loop or will give some ambiguity exception. But the same works fine and the second method is called when i give this url http://mysite:1234/mycontroller

What made MVC engine to choose the second method and not the first?

Any idea why this happens?

like image 682
thinkmmk Avatar asked Apr 11 '12 06:04

thinkmmk


1 Answers

Phil Haack has a post on this matter: How a method becomes an action

In short: the ControllerActionInvoker uses reflection to find a method matches the action name.

The ActionNameAttribute redefines the name of the method.

Also be aware that the name of your View matches the ActionName, not the MethodName: the method Index will search for a view with the name "Test"

like image 106
Andrew Avatar answered Oct 09 '22 08:10

Andrew