使用不带路由值的 Url.Action 会截断 URL
我有一个大量使用 AJAX 的网站,为了将 URL 等内容放在合理的位置,我在页面上的脚本块中输出所需的 URL,然后在 Javascript 中使用它们稍后归档。
一个例子是:
在 Index.cshtml
<script>
if (!app.frontoffice)
app.frontoffice = {};
if (!app.frontoffice.urls)
app.frontoffice.urls = {};
if (!app.frontoffice.urls.index)
app.frontoffice.urls.index = "@Url.Action("index", "frontoffice", new { area = string.Empty, id = string.Empty })";
</script>
在 JS 文件中的某处
$(function() {
$("myButton").click(function(e) {
$.ajax({
url: app.frontoffice.urls.index,
data: {
id: 55
},
success: ...
error: ...
});
});
});
问题是生成的Url 的创建方式如下 - /frontoffice
,请注意它不包括 index
操作。这是因为在生成它的时候我们给了它一个空的id
,所以当我们使用它的时候,请求的Url实际上是/frontoffic/55',而不是
/frontoffice/index/55'..
UrlHelper
似乎正在从 url 中剔除操作名称。我可以使用另一种不会从 URL 中删除项目的方法吗? - 我希望能够找到一个清晰的、可重复使用的解决方案,因为这种事情在网站上随处可见。
谢谢
基隆
I've got a site that's using making heavy use of AJAX, and in-order to keep things like Urls in a sensible place, I'm outputting the required Urls in a script block on the page, and then using them in a Javascript file later.
An example of this would be:
In Index.cshtml
<script>
if (!app.frontoffice)
app.frontoffice = {};
if (!app.frontoffice.urls)
app.frontoffice.urls = {};
if (!app.frontoffice.urls.index)
app.frontoffice.urls.index = "@Url.Action("index", "frontoffice", new { area = string.Empty, id = string.Empty })";
</script>
In a JS file somewhere
$(function() {
$("myButton").click(function(e) {
$.ajax({
url: app.frontoffice.urls.index,
data: {
id: 55
},
success: ...
error: ...
});
});
});
The issue is that the generated Url is created like so - /frontoffice
, notice it's excluding the index
action. This is because when it was generated we gave it an empty id
, so when we come to use it, the Url that gets requested is actually /frontoffic/55', not
/frontoffice/index/55'..
The UrlHelper
seems to be culling the action name from url. Is there another method I can use that doesn't remove items from the Url? - I was hoping to get away with a clear, reusable solution as this kind of thing happens all over the site.
Thanks
Kieron
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 id 的占位符。
然后在你的 .js 文件中
You could use a placeholder for the id.
Then in your .js file
这可能需要在您的路线定义中加以注意。您可能仍然定义了类似的内容:
routes.MapRoute("Default", "{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional});
对于其中一个,我可能会删除它或在默认路由定义之上放置一些明确定义您生成的 URL 的内容。
This probably needs to be taken care of in your route definitions. You probably still have something like this defined:
routes.MapRoute("Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional});
For one I would probably remove this or put something that explicitly defines the URL you're generating above the default route definition.