简体   繁体   中英

How to include js files in asp.net MVC and have a valid path on all routes

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?

Use the Url Helper:

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

Hope that helps

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM