Ajax, asp.net mvc3 routes and relative urls

ajax, asp.net-mvc-3, javascript, jquery, relative-path

Solution

Personally I tend to use a global variable of the relative URL of the server in my view like:

var BASE_URL = '@Url.Content("~/")';

Then you can do things like :

$.get(BASE_URL + 'a/b/c'), function (data) {}, "json");

I would like to add that if you want it to be totally global, you could add it to your /Views/Shared/_Layout.cshtml instead.

Problem

I have an ASP.NET MVC3 application published to a url like this: ``` http://servername.com/Applications/ApplicationName/ ``` In my code, I am using jquery ajax requests like this: ``` $.get(('a/b/c'), function (data) {}, "json"); ``` When I run the application locally, the ajax request goes directly to the correct page (being an mvc route) because the local page ends with a "/" (`localhost/a/b/c`). However, when I publish to `http://servername.com/Applications/ApplicationName/`, the trailing "/" is not always present. The url could be `http://servername.com/Applications/ApplicationName`, which then causes the ajax request to try to load `http://servername.com/Applications/ApplicationNamea/b/c`, which fails for obvious reasons. I have already looked into rewriting the url to append a trailing slash, but A) It didn't work, and B) I feel like it's a poor solution to the problem, and that it would be better to configure the javascript urls to work properly regardless of the local folder setup. I did try "../a/b/c" and "/a/b/c", but neither seemed to work. Thanks in advance for the help!

Original source