root url javascript

Viewed 11129

I'm working on an .Net ASP MVC razor application

The root url on the server being "myWebSite.com/myApp/"

I need to find dynamically this url to have the right url to make some Ajax call to action like this

    $.ajax(
    {
        type: "POST",
        url: root + "/Controller/Action",
        data: ...
    }

I read a few things here and there but what I found doesn't work

"document.location.hostname" -> "myWebSite.com"
"location.host"              -> "myWebSite.com"
"window.location.pathname"   -> "/myApp/"

Last one sounded promissing but if I navigate in the website :

 for an url :  "myWebSite.com/myApp/Controller/Action?1" 
 "window.location.pathname"   -> "/myApp/Controller/Action"
4 Answers

I use this:

In razor:

Uri auxBaseUri = new Uri(Request.Url.GetLeftPart(UriPartial.Authority));
Uri baseUri = new Uri(auxBaseUri, Url.Content("~"));   

Then in the js I use:

var baseUrl = "@baseUri.ToString()";

$.ajax
({
    type: "POST",
    url: baseUrl + "Controller/Action",
    ...

It works on my machine and on the server. Hope it helps

Related