2011-04-17 78 views
3

我使用.NET 3.5,MVC 2和T4MVC 2.6.42 ...T4MVC - 可选参数处理

我有以下作用:

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" } 
); 

但是,当我尝试呼叫​​我得到一个“方法没有超载索引'需要'1'参数”例外。然而,调用MVC.Products.Index()的作品。

因为它默认为'1',我不应该忽略“page”参数吗?

注意:我试过默认页面参数为1的路线,没有工作。

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

+0

我们可以看到完整的堆栈跟踪吗? – 2011-04-17 19:54:59

+0

@KirkWoll对不起,我设法找到解决方案。显然,可选参数是一个C#4.0的东西([文档](http://msdn.microsoft.com/en-us/library/dd264739.aspx)指出VS2010)。奇怪的是,当我在C#3.0中声明类似的方法时,我没有遇到编译器错误。 – 2011-04-18 01:38:23

回答

0

就像我在我的柯克沃尔回应称以上,显然,optional parameters aren't supported in C# 3.0

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

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

然后MVC.Products.Index(“富”)的工作就像一个魅力,与任何C#版本。

0

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

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

然后我必须每次都传递null,在这种情况下,它几乎与传递默认值相同。其实这是我的第一个方法,但后来我厌倦了调用MVC.Products.Index(“foo”,null)。 – 2011-04-18 01:33:27

+0

,但你可以调用MVC.Products.Index(“foo”) – VinnyG 2011-04-18 13:53:27

+0

显然不是C#3。 – 2011-04-19 18:31:08

5

虽然你找出错误的C#版本的问题,为了将来的参考有一种这样做的方法。你可以写:

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

这使您可以添加对除了什么方法调用传递个人PARAM值

+0

这是一种方法。我会发布我找到的解决方案(我以前不能这样做,因为我必须等待24小时才能发布对自己问题的答案)。 – 2011-04-19 18:32:35