使用没有路由值的Url.Action会截断URL

问题描述

|| 我有一个正在大量使用AJAX的网站,为了将类似Urls的内容保持在合理的位置,我正在页面上的脚本块中输出所需的Urls,然后稍后在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\',not
/ frontoffice / index / 55 \'。
UrlHelper
似乎是在从URL中剔除动作名称。有没有我可以使用的另一种方法,该方法不会从“网址”中删除项目? -我希望能得到一个清晰,可重用的解决方案,因为这种情况在整个站点中都会发生。 谢谢 基隆     

解决方法

您可以使用占位符作为ID。
app.frontoffice.urls.index = function (id) {
    return \"@Url.Action(\"index\",\"frontoffice\",new { id = \"000\" })\".replace(\'000\',id);
}
然后在您的.js文件中
$(function() {
    $(\"myButton\").click(function(e) {
        $.ajax({
            url: app.frontoffice.urls.index(55),success: ...
            error: ...
        });
    });
});
    ,在您的路线定义中可能需要注意这一点。您可能仍然定义了以下内容:
routes.MapRoute(\"Default\",\"{controller}/{action}/{id}\",new { controller = \"Home\",action = \"Index\",id = UrlParameter.Optional});
例如,我可能会删除它或在默认路由定义上方放置一些明确定义要生成的URL的内容。