Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I create relative paths in javascript using MVC3?

I am having some difficulty aligning my paths without a hardcode in javascript. I am running an asp.net MVC3 web application.

If my path is of the form

var url = 'http://serverNameHardcode/websiteNameHardcode/service/service?param1=' + param;

Then things work fine when I do

 $.get(url,
        {},
        function (data) {alert('callback success');},'json');

I would like to create a relative path. I tried

var url = 'service/service?param1=' + param;

And this works when I run locally and also in Firefox, but not in IE7. When I publish to the server without the hardcode the callback never fires. I know MVC-3 adds some complexity to routing, but I do not know if it applies to this situation; so, I marked this question as such.

How should I setup my path so I don't need hardcodes?

like image 613
P.Brian.Mackey Avatar asked Mar 01 '26 23:03

P.Brian.Mackey


2 Answers

Just write out the app path as a global js variable from your master view, then compose links as

APPPATH + "path/whatever"
like image 144
BNL Avatar answered Mar 04 '26 11:03

BNL


Just had to solve this for one of my jQuery plugins, where it is preferable not to modify anything global (i.e. outside the scope of the plugin use) so I had to disregard the marked answer.

I also found that because I host DEV locally in IIS I could not use a root-relative path (as localhost is not the root).

The solution I came up with extended what I had already started with: a data-controller attribute specifying which controller to use in the element I am applying my plugin to. I find it preferable to data-drive the controller names so the components can be more easily reused.

Previous:

   <div data-controller="Section">

Solution:

   <div data-controller="@Url.Content("~/Section")">

This injects the server root (e.g. /Test.WindowsAzure.Apr2014/ before the controller name so I wind up with /Test.WindowsAzure.Apr2014/Section which is perfect for then appending actions and other parameters as you have. It also avoids having an absolute path in the output (which takes up extra bytes for no good reason).

In your case use something like:

// Assuming $element points to the element your plugin/code is attached to...
var baseUrl = $element.data('controller');
var url = baseUrl + '/service?param1=' + param;

Update:

Another approach we now use, when we do not mind injecting a global value, is Razor-inject a single global JavaScript variable onto window in the layout file with:

<script>
   window.SiteRoot = "@Url.Content("~/")";
</script>

and use it with

var url = window.SiteRoot + '/service?param1=' + param;
like image 26
Gone Coding Avatar answered Mar 04 '26 12:03

Gone Coding