DaveDev
DaveDev

Reputation: 42225

Overloading Controller Actions

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

Upvotes: 9

Views: 1677

Answers (3)

Shakeer Hussain
Shakeer Hussain

Reputation: 2546

I don't see a right answers here, So i want to post a right answer.

Yes, You can overload Action results in MVC by using ActionName attribute.

[ActionName("Get")]  
public ActionResult Get()
{
    return PartialView(/*return all things*/);
}

[ActionName("GetById")]  
public ActionResult Get(int? id)
{
   //code
}

Upvotes: 0

MrW
MrW

Reputation: 1210

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

Upvotes: 1

Matt Lacey
Matt Lacey

Reputation: 65586

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*/); 
} 

Upvotes: 4

Related Questions