views:

78

answers:

2

Hi Guys

I was a bit surprised a few minutes ago when I tried to overload an Action in one of my Controllers

I had

public ActionResult Get()
{
    return PartialView(/*return all things*/);
}

I added

public ActionResult Get(int id)
{
    return PartialView(/*return 1 thing*/);
}

.... and all of a sudden neither were working

I fixed the issue by making 'id' nullable and getting rid of the other two methods

public ActionResult Get(int? id)
{
    if (id.HasValue)
        return PartialView(/*return 1 thing*/);
    else
        return PartialView(/*return everything*/);
}

and it worked, but my code just got a little bit ugly!

Any comments or suggestions? Do I have to live with this blemish on my Controllers?

Thanks

Dave

+1  A: 

You can't overload actions in this way as you have discovered.

The only way to have multiple actions with the same name is if they respond to different verbs.

I'd argue that having a single method which handles both situations is a cleaner solution and allows you to encapsulate your logic in one place and not rely on knowing about having multiple methods with the same name which are used for different purposes. - Of course this is subjective and just my opinion.

If you really wanted to have separate methods you could name them differently so that they clearly indicate their different purposes. e.g.:

public ActionResult GetAll() 
{ 
    return PartialView(/*return all things*/); 
} 

public ActionResult Get(int id) 
{ 
    return PartialView(/*return 1 thing*/); 
} 
Matt Lacey
@Matt, good point. It should have been GetAll().
DaveDev
+1  A: 

In my opinion there it really makes sense what you're saying Dave. If I for example have a select that have the option of selecting everything, or a single record, I don't want to different methods for that, but rather have one method with an overload as the one Dave is showing in the example.

// MrW

MrW