How do I make JS know about the application root?

前端 未结 2 1343

I have some javascript that\'s referencing /jobs/GetIndex in an MVC project. This works great when I run it locally because I have a Controller ca

相关标签:
2条回答
  • 2020-11-22 13:55

    Add <base href="/jobs"> to your head tag. It will specify the root.

    This is further explained here https://docs.angularjs.org/guide/$location

    0 讨论(0)
  • 2020-11-22 14:00

    If you simply care about getting the root/base url of the site so you can append that to get the other url you are after, you may simply use / as the first character of your url.

    var urlToJobIndex2= "/jobs/GetIndex";
    

    Here is an alternate approach if you want more than just the app root (Ex : Specific urls( built using mvc helper methods such as Url.RouteUrl etc)

    You may use the Url.Content helper method in your razor view to generate the url to the app base, assign it to a javascript variable and use that in your other js code to build your other urls. Always make sure to use javascript namespacing when doing so to avoid possible issues with global javascript variables.

    If you want to get url to a specific action method, you may use the Url.Action or Url.RouteUrl helper methods.

    So in your razor view (Layout file or specific view), you may do this.

    <script>
        var myApp = myApp || {};  
        myApp.Urls = myApp.Urls || {};
        myApp.Urls.baseUrl = '@Url.Content("~")';
        myApp.Urls.jobIndexUrl= '@Url.Action("GetIndex","jobs")';
    </script>
    <script src="~/Scripts/PageSpecificExternalJsFile.js"></script>
    

    And in your PageSpecificExternalJsFile.js file, you can read it like

    var urlToJobIndex= myApp.Urls.jobIndexUrl;
    // Or With the base url, you may safely add the remaining url route.
    var urlToJobIndex2= myApp.Urls.baseUrl+"jobs/GetIndex";
    

    Here is a detailed answer about the same , but using this in a specific page/view

    Angular Js

    You might need the correct relative url(s) in your angular controller / services / directives.The same approach will work for your angular code as well. Simply build the js namespace object and use the angular value provider to pass the data to your angular controllers/services/directives as explained in this post in detail with example code.

    0 讨论(0)
提交回复
热议问题