【问题标题】:T4MVC - Dealing with optional parametersT4MVC - 处理可选参数
【发布时间】:2011-04-17 19:35:23
【问题描述】:

我正在使用 .NET 3.5、MVC 2 和 T4MVC 2.6.42...

我有以下操作:

public virtual ActionResult Index(string id, int page = 1)

还有以下路线:

routes.MapRoute(
    "Products", // Route name
    "Products/{id}", // URL with parameters
    new { controller = "Products", action = "Index", id = UrlParameter.Optional, page = UrlParameter.Optional }, // Parameter defaults
    new string[] { "Web.Controllers" }
);

但是当我尝试调用 MVC.Products.Index("anything") 时,我得到一个“方法 'Index' 没有重载需要 '1' 参数”异常。但是,调用 MVC.Products.Index() 可以。

难道我不能省略“page”参数,因为它默认为“1”吗?

注意:我试过在路由中默认page参数为1,没用。

注意2:也试过[Optional] Attribute没有成功。

【问题讨论】:

  • 我们能看到完整的堆栈跟踪吗?
  • @KirkWoll 抱歉,我设法找到了解决方案。显然,可选参数是 C# 4.0 的东西(documentation 状态 VS2010)。奇怪的是,当我在 C# 3.0 中声明这样的方法时,我没有收到编译器错误

标签: c# asp.net-mvc t4mvc


【解决方案1】:

虽然您发现了错误的 C# 版本的问题,但为了将来的参考,有一种方法可以做到这一点。你可以写:

MVC.Products.Index().AddRouteValue("id", "anything");

这使您可以在方法调用传入的内容之外添加单个参数的值。

【讨论】:

  • 这是一种方法。我将发布我找到的解决方案(我之前不能发布,因为我必须等待 24 小时才能发布我自己问题的答案)。
【解决方案2】:

只要让你的 int 可以为空,它就会起作用。

public virtual ActionResult Index(string id, int? page = 1)

【讨论】:

  • 那么我每次都必须传递 null ,在这种特殊情况下,这与传递默认值几乎相同。实际上这是我的第一种方法,但后来我厌倦了调用 MVC.Products.Index("foo",null)。
  • 但你可以调用 MVC.Products.Index("foo")
【解决方案3】:

就像我在上面对 Kirk Woll 的回复中所说的那样,optional parameters aren't supported in C# 3.0

我通过创建重载并使用NonAction Attribute 解决了这个问题:

[NonAction]
public ActionResult Index(string id)
{
    return Index(id, 1);
}

然后 MVC.Products.Index("foo") 就像一个魅力,任何 C# 版本。

【讨论】:

    猜你喜欢
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 2010-12-04
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多