Can you overload controller methods in ASP.NET MVC?

前端 未结 17 1685
无人共我
无人共我 2020-11-22 08:10

I\'m curious to see if you can overload controller methods in ASP.NET MVC. Whenever I try, I get the error below. The two methods accept different arguments. Is this some

17条回答
  •  悲&欢浪女
    2020-11-22 08:44

    Yes. I've been able to do this by setting the HttpGet/HttpPost (or equivalent AcceptVerbs attribute) for each controller method to something distinct, i.e., HttpGet or HttpPost, but not both. That way it can tell based on the type of request which method to use.

    [HttpGet]
    public ActionResult Show()
    {
       ...
    }
    
    [HttpPost]
    public ActionResult Show( string userName )
    {
       ...
    }
    

    One suggestion I have is that, for a case like this, would be to have a private implementation that both of your public Action methods rely on to avoid duplicating code.

提交回复
热议问题