7

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.

1
  • What about placing this javascript in a master page? Commented May 4, 2011 at 21:13

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Clever, I did not think of this approach. Thanks. All I did was just use a few paths like scriptfolder = '@Url.Content("~/Scripts/")', imagefolder = '@Url.Content("~/Images/")' and then just appended them to the current urls already there.
I just had a thought, what about for CSS where the styles are in a css file? if you have images or backgrounds to a folder but that needs to be relative path.
Paths in CSS are relative to the CSS file, not the loaded page. So you can do paths such as background-image: url('../images/image1.png');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.