简体   繁体   English

如何在asp.net MVC中包含js文件,并在所有路由上都有一个有效的路径

[英]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. 我创建了一个默认的ASP.net MVC项目。 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: 然后,我需要添加一个javascript文件,并通过将文件从解决方案资源管理器拖到页面来添加以下行:

<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: 当我访问该网站并从浏览器中查看html时,我看到:

<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. CSS文件相对路径是固定的,但JS文件没有。 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: 使用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. 如果您更改文件的名称,那么这本身就是一个不同的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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