tags:

views:

957

answers:

2

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: http://stackoverflow.com/questions/436866/can-you-overload-controller-methods-in-asp-net-mvc

+1  A: 

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).

Alconja
This is pretty much what I do, but I write it as public ActionResult DoSomething(int? id, string name)and just do a check for String.IsNullOrEmpthy(name) in the method.
Chris
A: 

I guess it is not. Since I found that the MVC framework didn't really care what you put in the parameter list, for example, my action is like:

public ActionResult Index(int id) {...}

It is ok to request like this: Domain.com/Index.aspx or Domain.com/Index.aspx?id=012901 or even Domain.com/Index.aspx?login=938293

Since overloading in programming language means that you select different functions (with same name) using the input parameters, but MVC in this case didn't care about it! So other than ActionVerb overloading, I think it is not ok.

xandy
Yes but I believe it is because of your URL syntax, where as I'm using {controller}/{action}/{id} type syntax.
4thSpace
I haven't tried the syntax like yours to test overloading, but it sounds it is still not possible since ASP.net MVC will still treat the id(parameter) as a string and pass it to the action (may try to typecast it if the action accepts only int, but in that case, some error might raise when the id is not integer)
xandy