Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Relative URL Paths - Javascript

I have an issue with relative paths whereby when the web app is running off subdirectory of the domain, the paths are not correct. e.g. http://www.example.com/webapp/

If I use @Url.Content("~/path/to/action") on the page it is fine. I can even embed the @Url.Content("") inside the javascript script. I want to clean up the page I wanted to put the javascript inside a js file and reference that. Now that the @Url.Content is being called inside the javascript file, it doesn't seem to work (probably for obvious reasons). How can I get around this issue?

I had a look at the <base /> but that doesn't seem to work.

like image 430
fes Avatar asked May 04 '11 21:05

fes


1 Answers

Now that you moved everything into a separate js file, the file is being served as static content, and the Razor syntax is not being parsed.

If you need relative paths inside of your js which might change, then you should include a script in each page which sets a path var, and use @Url.Content(...) in this script, e.g.,

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

Then, declare the pathToAction var in your js file, and use it as needed.

like image 64
counsellorben Avatar answered Sep 28 '22 07:09

counsellorben