sam sam - 1 month ago 11
ASP.NET (C#) Question

MVC "~" path in javascript

I use JavaScript code to call an MVC web API. It works fine when the current path is:

http://localhost/myApp/Administrator


but it fails when current path is:

http://localhost/myApp/Administrator/


I get the error
The resource cannot be found
. Below is the code:

$.getJSON("api/UserApi",
function (data) {
...
});


I don't want to use an absolute URL in the code, e.g.:

$.getJSON("http://localhost/myApp/api/UserApi",
function (data) {
...
});


The absolute URL does work fine, but lacks flexibility. Is there a way to do the same thing as below?

$.getJSON("~/api/UserApi",
function (data) {
...
});


ASP.NET supports the replacement of the "~" character with the current application's root path, e.g.:

http://localhost/myApp


However, the "~" character is not supported in JavaScript files. How do I accomplish the same thing?

The JavaScript is in a standalone file that cannot use ASP.NET statements like
Url.Content
. Is there a better way to do it?

I've found the following method. Are there any better solutions?:

1) Write the code below in a .cshtml file

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


2) Read the
currentDomain
variable from the .js file:

$.getJSON(currentDomain + "/api/UserApi",
function (data) {
...
});

Answer

If you're trying to get link to an action, you can define JavaScript variales in your view that will be populated with Url.Action:

<script type="text/javascript">
    var userApiPath = '@(Url.Action("userApi", "api"))';
</script>

And later use this variable in your JS file:

$.getJSON(userApiPath,          
    function (data) {
});

If you want a general path to your app, you can do something like that:

<script type="text/javascript">
    var path = '@(string.Format("{0}://{1}{2}",
                Request.Url.Scheme,
                Request.Url.Host,
                (Request.Url.IsDefaultPort) ? "" : string.Format(":{0}",
                Request.Url.Port)))';
</script>

And later use this variable somewhere in your JS files. Of course you don't have to use string.Format to do this, that's just an example.

EDIT:

You may also consider using RazorJS.