Overloading Controller Actions

删除回忆录丶 提交于 2020-01-03 08:38:15

问题


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:


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



回答2:


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




回答3:


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
}


来源:https://stackoverflow.com/questions/2433766/overloading-controller-actions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!