Can you overload controller methods in ASP.NET MVC?

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 something that cannot be done?

The current request for action 'MyMethod' on controller type 'MyController' is ambiguous between the following action methods:


You can use the attribute if you want your code to do overloading.

[ActionName("MyOverloadedName")]

But, you'll have to use a different action name for the same http method (as others have said). So it's just semantics at that point. Would you rather have the name in your code or your attribute?

Phil has an article related to this: http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx


Yes. I've been able to do this by setting the HttpGet / HttpPost (or equivalent AcceptVerbs attribute) for each controller method to something distinct, ie, 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.


Here's something else you could do... you want a method that is able to have a parameter and not.

Why not try this...

public ActionResult Show( string username = null )
{
   ...
}

This has worked for me... and in this one method, you can actually test to see if you have the incoming parameter.


Updated to remove the invalid nullable syntax on string and use a default parameter value.

链接地址: http://www.djcxy.com/p/48124.html

上一篇: ASP.NET MVC3:DropdownList中的对象在控制器中为空

下一篇: 你可以在ASP.NET MVC中重载控制器方法吗?