ASP.Net Mvc 3 Url.Action 方法使用先前请求中的参数值
当使用 Url.Action
帮助器自动生成 URL 时,如果页面包含类似于以下内容的行
@Url.Action("编辑","学生")
预计会生成一个类似 domain/student/edit
的 url 并按预期工作。 但是,如果请求的 url 包含一些参数,例如 domain/student/edit/210
,则上述代码将使用上一个请求中的这些参数并生成类似的内容,即使我没有提供任何此类参数Action
方法。
简而言之,如果请求的 url 包含任何参数,则页面的任何自动生成的链接(为该请求提供服务)也将包含这些参数,无论我是否在 Url.Action
中指定它们。方法。
出了什么问题?
When Urls are autogenerated using the Url.Action
helper, if a page contains a line similar to
@Url.Action("Edit","Student")
is expected to generate a url like domain/student/edit
and its working as expected.
But if the requested url contains some parameters, like domain/student/edit/210
, the above code uses these parameters from the previous request and generates something similar even though I've not provided any such parameter to the Action
method.
In short, if the requested url contains any parameters, any auto generated links of the page (served for that request) will include those parameters as well no matter if I specify them or not in the Url.Action
method.
What's going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用达林在这个类似问题中的答案。
Use Darin's answer from this similar question.
奇怪的是,似乎无法重现问题:
在
Index.cshtml
内部:现在,当我请求
/home/index/123
时,url 帮助程序会生成/home /about
正如预期的那样。没有幽灵参数。那么您的场景有何不同?更新:
现在您已经澄清了您的场景,似乎您有以下内容:
并且在
Index.cshtml
中您尝试使用:如果您请求
/home/index/123
这会生成/home/index/123
而不是预期的/home/index
(或者简单地考虑默认值的/
)。此行为是设计使然。如果您想更改它,您将必须编写自己的助手,该助手会忽略当前的路线数据。它可能如下所示:
这将生成您期望的正确 URL。当然,这很丑陋。我建议您将其封装到可重用的助手中。
Weird, can't seem to reproduce the problem:
and inside
Index.cshtml
:Now when I request
/home/index/123
the url helper generates/home/about
as expected. No ghost parameters. So how does your scenario differs?UPDATE:
Now that you have clarified your scenario it seems that you have the following:
and inside
Index.cshtml
you are trying to use:If you request
/home/index/123
this generates/home/index/123
instead of the expected/home/index
(or simply/
taken into account default values).This behavior is by design. If you want to change it you will have to write your own helper which ignores the current route data. Here's how it might look:
This will generate the proper url you were expecting. Of course this is ugly. I would recommend you encapsulating it into a reusable helper.
使用使用参数并提供 null 的 ActionLink 重载
Use ActionLink overload that uses parameters and supply null
例如,您可以为此操作注册自定义路由:
然后您可以使用
url.RouteUrl("Domain_EditStudentDefault")
url RouteUrl 辅助重写,仅使用routeName
参数来生成不带参数的 url 。You could register custom route for this action for example:
you then could use
url.RouteUrl("Domain_EditStudentDefault")
url RouteUrl helper override with onlyrouteName
parameter which generates url without parameters.