我正在使用 .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”吗?

注意: 我试过将路由中的页面参数默认为 1,但没有奏效。

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

最佳答案

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

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

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

关于c# - T4MVC - 处理可选参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5695931/

10-17 01:12