3

我正在使用 .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] 属性,但没有成功。

4

3 回答 3

5

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

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

除了方法调用传入的内容之外,这还允许您添加单个参数的值。

于 2011-04-18T04:22:00.757 回答
0

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

public virtual ActionResult Index(string id, int? page = 1)
于 2011-04-17T21:16:35.503 回答
0

就像我在上面对 Kirk Woll 的回复中所说的那样,显然C# 3.0 不支持可选参数

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

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

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

于 2011-04-19T18:34:39.200 回答