Error already defines a member called 'Index' with the same parameter types

别等时光非礼了梦想. 提交于 2021-02-17 05:30:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!