4

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?

Vivian River
  • 31,198
  • 62
  • 198
  • 313
  • 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 Nov 27 '13 at 15:42

1 Answers1

1

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;
pwnyexpress
  • 1,016
  • 7
  • 14
  • This is not the answer I'm looking for. Your answer is very similar to what I've proposed here. What I want to know is whether or not the framework has some built-in mechanism for handling this. – Vivian River Feb 05 '13 at 18:17
  • If the .NET framework has a way of altering a client browser's implementation of javascript? – pwnyexpress Feb 05 '13 at 18:26
  • ASP.net does create some variables and functions in JavaScript that allow you to reference some server-side things. __doPostBack is probably the best-known of these. I was wondering if there might be some other function or variable created by the framework I could refer to and count on it being there. – Vivian River Feb 05 '13 at 18:29