Overloading Controller Actions

2019-06-16 05:34发布

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

3条回答
走好不送
2楼-- · 2019-06-16 06:15

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*/); 
} 
查看更多
神经病院院长
3楼-- · 2019-06-16 06:24

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

查看更多
仙女界的扛把子
4楼-- · 2019-06-16 06:26

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
}
查看更多
登录 后发表回答