Reputation: 3752
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
called JobsController
. When I deploy it, I deploy the application to a 'Jobs' subfolder, which means the URL should become http://site/jobs/jobs/GetIndex
but it's going to http://site/jobs/GetIndex
, I presume because the javascript doesn't know what the 'root URL' is, and uses the site as the root. How can I get it to work in both environments?
Upvotes: 3
Views: 3926
Reputation: 218892
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.
Upvotes: 8
Reputation: 280
Add <base href="/jobs">
to your head tag. It will specify the root.
This is further explained here https://docs.angularjs.org/guide/$location
Upvotes: 0