ASP.NET MVC resolve urls in javascript

后端 未结 4 1224
执笔经年
执笔经年 2020-12-25 08:11

I am loading up some content via jQuery.load(\'/Business/Tags\'), which works well when using my local webserver. But when using iis this does not resolve correctly. I hav

4条回答
  •  旧巷少年郎
    2020-12-25 08:32

    As for me I'm using Url.Action/Url.RouteUrl helpers with JavaScript/jQuery where it is possible:

    $.load('<%= Url.Action("Tags", "Business") %>')
    

    or

    $.load('<%= Url.RouteUrl("BusinessTagsRoute") %>')
    

    In other cases I'm using ResolveUrl helper (from MVCContrib or your could write your own):

    $.load('<%= Url.ResolveUrl("~/Business/Tags") %>')
    

    UPDATED:

    It is also possible to create special controller for your JavaScript/jQuery with actions, returning PartialViews with JavaScript:

    public ActionResult YourJavaScript()
    {
        Response.ContentType = "application/x-javascript";
        return PartialView("YourJavaScript");
    }
    

    Then in your YourJavaScript.ascx you can use JavaScript/jQuery code with WebForms server tags. I still recommend not to use hardly coded Urls in jQuery/AJAX

提交回复
热议问题