13

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 4

26

In asp.net mvc, using razor view engine, I got this in my layout:

<script type="text/javascript">
 var baseUrl = "@Url.Content("~")";
</script>

That way we can define application base url as javascript object that is accessible from everywhere.

Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to find this. Use realtive path:

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

This will go in as <root>/Controller/Action

1 Comment

That's actually what i use locally but on the server I have to write url: "MyApp/Controller/Action" that's the only way it seems to work but it's a pain in the ass to have to change the link everytime I put it on the server and even if it worked, i need to display some icon on a googlemap, for that i need i also need the correct root
0

What about this?

var root = "<%=Request.ApplicationPath%>";
alert(root);

Does it give correct root URL?

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.