问题
In my Controller i have the following 2 methods;
[ActionName("index")]
public ActionResult Index()
{
return View();
}
and
public ActionResult Index()
{
var m =MyMod();
return View(m);
}
Even though i used [ActionName("index")]
i get an error saying that Error 1 Type 'MyProject.Controllers.MyController' already defines a member called 'Index' with the same parameter types
How can i prevent this ?
回答1:
No, this is not possible, you cannot have 2 actions with the same name on the same controller using the same HTTP verb. Also from C#'s perspective you cannot have 2 methods on the same class with the same name and same parameters. The compiler won't let you do that.
You could make one of the 2 actions be accessible with a different HTTP verb. This is usually the convention when you have 2 actions with the same name. The first is used to render a view and the second is decorated with the [HttpPost]
attribute and used to process the form submit from the view. The post action also takes a view model as parameter containing the form submission fields. So the 2 methods have different signatures and it will make the compiler happy. Here's the recommended approach:
public ActionResult Index()
{
MyViewModel model = ...
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
...
}
回答2:
From the compiler's point of view, those two methods are the same. They have the same name, return type and parameters (in this case none). That is why you are getting the error.
Did you mean to create an overload for Index taking a parameter ?
来源:https://stackoverflow.com/questions/15012213/error-already-defines-a-member-called-index-with-the-same-parameter-types