MVC3 Relative URL Paths - Javascript

11,414

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.

Share:
11,414
fes
Author by

fes

Updated on June 04, 2022

Comments

  • fes
    fes almost 2 years

    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.

  • fes
    fes almost 13 years
    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.
  • fes
    fes almost 13 years
    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.
  • moonpatrol
    moonpatrol almost 12 years
    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');