开发者

Using Url.Action with no route values truncates the URL

开发者 https://www.devze.com 2023-03-08 00:29 出处:网络
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

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 requ开发者_如何学Cested 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


You could use a placeholder for the id.

app.frontoffice.urls.index = function (id) {
    return "@Url.Action("index", "frontoffice", new { id = "000" })".replace('000', id);
}

Then in your .js file

$(function() {
    $("myButton").click(function(e) {
        $.ajax({
            url: app.frontoffice.urls.index(55),
            success: ...
            error: ...
        });
    });
});


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消