在 ASP.NET MVC 的母版页中使用脚本 [英] Using scripts in a master page with ASP.NET MVC
问题描述
我对 ASP.NET MVC 还很陌生,我在脚本方面遇到了一些麻烦……特别是,我想在大多数页面中使用 jQuery,因此将它放在母版页中是有意义的.但是,如果我这样做(来自我的 ~/Views/Shared/Site.Master
):
I'm fairly new to ASP.NET MVC, and I'm having a little trouble with scripts... in particular, I want to use jQuery in most pages, so it makes sense to put it in the master page. However, if I do (from my ~/Views/Shared/Site.Master
):
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
那么这实际上是由客户决定的——当然,这只有在我们当前的路线恰好具有正确数量的级别时才有效.以 ~/Scripts/...
开头不起作用.以 /Scripts/...
开头仅当项目位于站点根目录时才有效(我不想假设).
Then that is literally what goes down to the client - which of course only works if our current route happens to have the right number of levels. Starting with ~/Scripts/...
doesn't work. Starting with /Scripts/...
would only work if the project was at the site root (which I don't want to assume).
我有一种工作方法(我将在下面发布)-但是:我错过了什么吗?
I have one working approach (I'll post below) - but: am I missing something?
我宁愿不必涉及脚本管理器,因为这似乎破坏了 ASP.NET MVC 模型的简单性……还是我太担心了?
I'd rather not have to involve a script-manager, as that seems to defeat the simplicity of the ASP.NET MVC model... or am I worrying too much?
这是我让它工作的方法,它也适用于非平凡的虚拟 - 但它似乎过于复杂:
Here's the way I can get it working, which works also for non-trivial virtuals - but it seems over-complicated:
<script src="<%=Url.Content("~/Scripts/jquery-1.2.6.js")%>" type="text/javascript"></script>
推荐答案
我有一个 AppHelper 类,其中包含一些添加脚本引用的方法:
I have a AppHelper class with some methods for adding script references:
public static string ReferenceScript(string scriptFile)
{
var filePath = VirtualPathUtility.ToAbsolute("~/Scripts/" + scriptFile);
return "<script type="text/javascript" src="" + filePath + ""></script>";
}
因此在您的母版页中您可以使用:
so in your master page you can use:
<%= AppHelper.ReferenceScript("jquery-1.2.6.js") %>
这篇关于在 ASP.NET MVC 的母版页中使用脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!