MVC3 Relative URL Paths - Javascript

I have a problem with relative paths, when a web application is launched from a subdirectory of a domain, the paths are not correct. e.g. http://www.example.com/webapp/

If I use @Url.Content("~/path/to/action") on the page, that's fine. I can even embed @Url.Content("") in a javascript script. I want to clear the page, I wanted to put javascript in a js file and reference this. Now when @Url.Content is called inside the javascript file, it does not seem to work (probably for obvious reasons). How can I get around this problem?

I looked at <base /> , but that doesn't seem to work.

+7
source share
1 answer

Now that you have moved everything to a separate js file, the file is treated as static content and the Razor syntax is not parsed.

If you need relative paths inside js that can change, you should include a script on every page that sets the var path, and use @ Url.Content (...) in this script, e.g.

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

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

+12
source

All Articles