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:
In C#, there might be two or more methods in a class with the same name but different numbers, types, and order of parameters, it is called method overloading.
While ASP.NET MVC will allow you to have two actions with the same name, . NET won't allow you to have two methods with the same signature - i.e. the same name and parameters. You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.
Method overloading can be done in a web service with the following things: By changing the number of parameters used. By changing the order of parameters. By using different data types for the parameters.
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, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With