ASP.NET MVC - URL路由参数问题
我有这个路由声明:
routes.MapRoute(
// Route name
"WhiteLabelPartners",
// URL with parameters
"partners/{partnerName}/{controller}/{action}/{id}",
// Parameter defaults
new { partnerName = "", controller = "", action = "index", id = UrlParameter.Optional }
);
当我尝试这个 URL 时:
/partners/a/savings/index/1
...它工作正常。 Savings 控制器的索引操作被命中。
但是,当我尝试这个 URL 时:
/partners/a/savings/index
我得到一个“未找到”。
如果我的 {id} 参数有一个 UrlParameter.Optional,为什么仍然需要它?
有人能解释一下吗?如何使 {id} 参数可选?
谢谢
I have this route declaration:
routes.MapRoute(
// Route name
"WhiteLabelPartners",
// URL with parameters
"partners/{partnerName}/{controller}/{action}/{id}",
// Parameter defaults
new { partnerName = "", controller = "", action = "index", id = UrlParameter.Optional }
);
When I try this URL:
/partners/a/savings/index/1
...it works fine. The index action of the Savings controller is hit.
But, when I try this URL:
/partners/a/savings/index
I get a "not found".
If I have a UrlParameter.Optional for the {id} parameter, why is it still being required?
Could anyone explain? How can I make the {id} parameter optional?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确保您的索引操作不需要参数。
如果在您的控制器上,您的 Index 操作如下所示:
public ActionResult Index(int id)
它将需要在 ID 字段中传递一个参数,因为您没有在路由中提供默认值。这可能就是您收到“未找到”错误的原因,因为它找不到匹配的操作。它期望:
public ActionResult Index()
您可以不带参数保留 Index() 操作,并在 Index() 操作中检索传入的“id”参数的值(如果有)通过 :
RouteData.Values["id"]
使用它。
让我们知道这是否适合您。
(注意:我想发布像 tejs 这样的评论(但没有看到添加评论的链接?!),要求您在控制器上显示您的 Index 方法签名,所以请务必将其包含在问题中。)
Make sure your Index Action does not expect a parameter.
If, on your controller, your Index action looks like this :
public ActionResult Index(int id)
it will need a param to be passed in the ID field, as you are not providing a default value in the route. That's probably why you are getting the 'not found'error as it cannot find a matching action. It is expecting :
public ActionResult Index()
You could leave the Index() action without a parameter and from within the Index() action, retrieve the value of the passed in 'id' parameter, if any via :
RouteData.Values["id"]
to use it.
Let us know if that works for you.
(note: i wanted to post a comment like tejs(but dont see a link to add comment?!), to ask you to show your Index method signature on the controller, so please do include that in the question.)