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

后端 未结 2 1628
感动是毒
感动是毒 2021-01-28 18:19

In my Controller i have the following 2 methods;

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

and

 public ActionResult Index()
 {         


        
2条回答
  •  旧时难觅i
    2021-01-28 19:09

    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)
    {
        ...
    } 
    

提交回复
热议问题