可选的路线参数和动作选择
我使用默认路由定义:
{controller}/{action}/{id}
其中id = UrlParameter.Optional
。据我了解,这意味着当 id
不是 URL 的一部分时,该路由值将不存在于 RouteValues
字典中。
所以这似乎也是完全可能的(都是 GET):
public ActionResult Index() { ... } // handle URLs: controller/action
public ActionResult Index(int id) { ... } // handle URLs: controller/action/id
当 id
丢失时,第一个操作将被执行,但是当 id
存在时,第二个操作将执行。很好,但是它不起作用。它无法解析操作。
我怎样才能做到这一点?
我正在考虑编写一个自定义操作方法选择器属性,例如:
[RequiresRouteValue(string valueName)]
这将使使用这种操作方法成为可能。但这是唯一的方法吗?
有什么内置的东西是我可以坚持的吗?
I use the default route definition:
{controller}/{action}/{id}
where id = UrlParameter.Optional
. As much as I understand it this means when id
is not being part of the URL this route value will not exists in the RouteValues
dictionary.
So this also seems perfectly possible (both GET):
public ActionResult Index() { ... } // handle URLs: controller/action
public ActionResult Index(int id) { ... } // handle URLs: controller/action/id
When id
is missing the first action would be executed, but when id
is present, the second one would execute. Fine, but it doesn't work. It can't resolve actions.
How can I accomplish this?
I'm thinking of writing a custom action method selector attribute like:
[RequiresRouteValue(string valueName)]
This would make it possible to use this kind of action methods. But is this the only way of doing it?
Is there something built-in I can hang on to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用其中之一:
或者只使用一个带有可为空参数的参数:
编辑:
像这样的东西会起作用吗?
Use either:
Or just have one with a nullable param:
EDIT:
Would something like this work?
从无法确定操作的例外情况来看,很明显,首先解析操作,然后数据绑定器发挥作用并检查操作的参数并尝试将数据绑定到它们。很有道理。
这是完全有道理的。首先尝试将值数据绑定到所有可能的类型并查看我们得到什么,然后寻找适当的操作是没有意义的。这几乎是不可能的。
所以。由于操作选择是这里的问题,我想解决这个问题的最佳(也是唯一)方法(如果我不想使用多方面的单一操作方法)是编写一个自定义操作方法选择器属性 。
您可以在我的博客上阅读所有详细信息并获取代码:
提高 Asp.net MVC 可维护性和 RESTful 一致性
Well from the exception that action can't be determines is pretty clear that actions are resolved first then data binder comes into play and examines action's parameters and tries to data bind values to them. Makes perfect sense.
This makes perfect sense. There would be no point in first trying to data bind values to all possible types and see what we get and then look for an appropriate action. That would be next to impossible.
So. Since action selection is the problem here I guess the best (and only) way to solve this (if I don't want to use a multifaceted single action method) is to write a custom action method selector attribute.
You can read all the details and get the code on my blog:
Improving Asp.net MVC maintainability and RESTful conformance