4
votes

I'm working on an ASP.net MVC application. One thing that I really like about ASP.net MVC is the way that it allows you to refer to relative paths in server-side code. I was wondering if there is some standardized way of doing this in client-side code.

I have a way of doing this. I write the following in my layout page.

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

Making this the first script in my layout page, I can refer to relative paths from any .js file using the ApplicationPath variable. This seems to work well, but I'm left wondering if there is some built-in way of working with relative paths in JavaScript. This works well for me, but someone else might use a different convention.

Does ASP.net MVC 4 have some standardized way of referring to relative paths in JavaScript?

1
I was also looking for a solution. Did you ever find a cleaner way? What do you think about using a cookie and reading the cookie in the javascript so that there wouldn't be a need for a separate script?edhedges

1 Answers

1
votes

I usually do this in my masterpage header:

<script type="text/javscript">
    var conf = { baseUrl: '<%=VirtualPathUtility.ToAbsolute("~/")%>' };
</script>

Then, anywhere else in js you can just use:

var fullUrl = conf.baseUrl + '/somePath';

Also, you can always get the base domain in JS using:

var baseUrl = window.location.hostname;