views:

1783

answers:

2

I created a default ASP.net MVC project. In the Master page I have the following at the top

<head runat="server">
    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
</head>

I then need to add a javascript file and added the line as follows by dragging the file from the solution explorer to the page:

<head runat="server">
    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
</head>

When I access a the site and look at the html from the browser I see this:

<head><title> 

    Index

</title><link href="Content/Site.css" rel="stylesheet" type="text/css" /> 
    <script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>  
</head>

The CSS file relative path was fixed but the JS file not. The site will be deployed to a different folder on the server than the root which I get on my development box.

Is there a proper way to do this?

+9  A: 

Use the Url Helper:

<script type="text/javascript" src="<%=Url.Content("~/Content/script/MyFile.js")%>"></script>

Hope that helps

Lewis
This fixes the issue with installing the site in a subdirectory as the ~ is replaced with the path to the root of the site. But the problem that when I get to the root the js file is in the Scripts folder under the root and not ../../Scripts remains. Since MVC will route to diffrent subfolders then the script is not allways available from all routes.I gave you +1 since at least now I have a way to hardcode the paths relative to the root. But I'll wait to see if someone can explain why it works for the CSS out of the box and not for JS.
jvanderh
I think the issue is not css vs Javascript but that you simply have your css inside your conetne folder and not your script
Lewis
+2  A: 

You can create a helper method that does something like this:

<%= Helper.IncludeJavascriptFile("Menu.js") %>

and then in that helper you do something like:

public string IncludeJavascriptFile(string fileName){
    return Url.Content("<root>/Javascript/Files/" + fileName);
}

Then you can call that helper method from your view. If you decide to change the location of the files, it's only in one location you have to worry about it. If you change the name of the files, that's a different problem in and of itself.

MunkiPhD
+1 for mantainability.
jvanderh