Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading asp.net MVC controller methods with same verb?

Tags:

asp.net-mvc

All the examples I've seen for overloading usually have only two methods of the same name with different parameters and one using the GET verb while the other uses POST. Is it possible to do two or more overloads on the same method, all with the same verb?

Here's an example of what I'm referring to: Can you overload controller methods in ASP.NET MVC?

like image 538
4thSpace Avatar asked Jul 17 '09 06:07

4thSpace


1 Answers

I don't think you can overload the same action name with the one verb by default. As that other thread you point to says, you can overload the methods & then use an attribute to change the action that maps to the method, but I'm guessing that's not what you're looking for.

Another option that I've used before (depends on how complex/different your overloads are) is to simply use nullable values for the parameters & effectively merge your different signatures together. So instead of:

public ActionResult DoSomething(int id)...
public ActionResult DoSomething(string name)...

just have:

public ActionResult DoSomething(int? id, string? name)

Not the nicest solution, but if one overload just builds on another then its not too bad a compromise.

One final option that may be worth giving a go (I haven't tried it & don't even know if it'll work, but logically it should), is to write an implementation of the ActionMethodSelectorAttribute that compares the parameters passed in the ControllerContext to the method signature & tries to make a best match (i.e. try to resolve the ambiguity a bit more strictly than the default implementation).

like image 134
Alconja Avatar answered Oct 21 '22 12:10

Alconja