重载控制器操作 [英] Overloading Controller Actions

查看:164
本文介绍了重载控制器操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点惊讶几分钟前,当我试图超载在我其中一个控制器的动作

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

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

我添加

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

......和所有突然被没有工作

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

我通过'ID'可空,摆脱其他两种方法的固定问题

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

和它的工作,但我的code刚刚有点难看!

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?

感谢

戴夫

推荐答案

您不能以这种方式,你已经发现超载行为。

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

这篇关于重载控制器操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆