T4MVC-处理可选参数

| 我正在使用.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()
可行。 由于默认值为\'1 \',我是否应该忽略\“ page \”参数吗? 注意:我已经尝试将路由中的page参数默认设置为1,但是没有用。 注意2:还尝试了[Optional]属性,但没有成功。     
已邀请:
尽管您发现了错误的C#版本的问题,但为了将来参考,有一种解决方法。你可以写:
MVC.Products.Index().AddRouteValue(\"id\", \"anything\");
这样,除了方法调用传递的内容外,还可以添加各个参数的值。     
只需将您的int设为可为空,它将起作用。
public virtual ActionResult Index(string id, int? page = 1)
    
就像我在上面对Kirk Woll的回复中所说的那样,显然,C#3.0不支持可选参数。 我通过创建重载并使用NonAction属性解决了该问题:
[NonAction]
public ActionResult Index(string id)
{
    return Index(id, 1);
}
然后,对于任何C#版本,MVC.Products.Index(\“ foo \”)都像一个超级按钮一样工作。     

要回复问题请先登录注册