Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

like image 685
Papa Burgundy Avatar asked Jan 12 '09 20:01

Papa Burgundy


People also ask

Can you overload methods in C#?

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.

Can we have two action methods with same name in MVC?

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.

Is method overloading possible in web API?

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.


2 Answers

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

like image 198
JD Conley Avatar answered Sep 19 '22 13:09

JD Conley


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.

like image 25
tvanfosson Avatar answered Sep 17 '22 13:09

tvanfosson