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

后端 未结 2 1619
感动是毒
感动是毒 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条回答
  • 2021-01-28 19:03

    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 ?

    0 讨论(0)
  • 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)
    {
        ...
    } 
    
    0 讨论(0)
提交回复
热议问题