Ajax, asp.net mvc3 and relative urls

I have an ASP.NET MVC3 application published at the url:

http://servername.com/Applications/ApplicationName/

In my code, I use jquery ajax queries as follows:

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

When I run the application locally, the ajax request goes directly to the correct page (which is mvc traffic), because the local page ends with the "/" ( localhost/a/b/c) character .

However, when I publish to http://servername.com/Applications/ApplicationName/, the final "/" is not always present. The URL may be http://servername.com/Applications/ApplicationName, after which the ajax request tries to load http://servername.com/Applications/ApplicationNamea/b/c, which for obvious reasons is not executed.

I already looked at rewriting url to add a trailing slash, but A) That didn't work, and B) I feel this is a bad solution to the problem, and that it would be better to set javascript urls to work correctly regardless of setting the local folder.

I tried "../a/b/c" and "/ a / b / c", but none of them worked.

Thanks in advance for your help!

+3
source share
3 answers

Personally, I tend to use a global variable relative server URL in my view, for example:

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 completely global, you can add it to your / Views / Shared / _Layout.cshtml.

+11
source

JavaScript, MVC Url Url.Action Url.Content. _Layout.cshtml, , .

<script type="text/javascript">
    function UrlAction(action, controller) {
        var url = ('@Url.Action("--Action--","--Controller--")').replace("--Action--", action).replace("--Controller--", controller);
        return url;
    }

    function UrlContent(url) {
        var path = "@Url.Content("~/--file--")";
        path = path.replace("--file--", url.replace('~/', ''));
        return path;
    }
</script>

:

var url = UrlAction('AvailableAssetClasses', 'Assessment');
var url2 = UrlContent('~/Images/calendar.gif');
+3

Url URL- ASP.NET MVC . , script :

<script type="text/javascript">
    var url = '@Url.Action("a", "b")';
    $.get(url, function (data) {}, "json");
</script>

script javascript ( ), , URL- DOM. , HTML5:

<div data-url="@Url.Action("a", "b")" id="foo">Click me</div>

javascript:

$('#foo').click(function() {
    var url = $(this).data('url');
    $.get(url, function (data) {}, "json"); 
});

AJAXifying , , url:

$('a#someAnchor').click(function() {
    var url = this.href;
    $.get(url, function (data) {}, "json"); 
    return false;
});
+3

All Articles