在ASP.NET MVC母版页使用脚本 [英] Using scripts in a master page with ASP.NET MVC
问题描述
我是相当新的ASP.NET MVC,和我有一个小麻烦的脚本......特别是,我想使用jQuery在大多数的网页,所以是有意义的把它的母版页。但是,如果我这样做(从我的〜/查看/共享/的Site.Master
):
<脚本的src =../../脚本/ jQuery的-1.2.6.js类型=文/ JavaScript的>< / SCRIPT>
然后就是字面上什么下降到客户端 - 这当然只是如果我们的当前的路线碰巧有水平的正确数量的作品。开始与〜/脚本/...
不起作用。开始与 /脚本/...
只会工作,如果该项目是在站点根目录(我不想承担)。
我有一个工作方法(我会后下) - 但是:我失去了一些东西。
?我宁愿没有涉及脚本管理器,因为这似乎击败ASP.NET MVC模型的简单......还是我担心太多了?
下面是该方法可以让我得到它的工作,其工作方式也为不平凡的虚 - 但似乎过于复杂的:
<脚本SRC =<%= Url.Content(〜/脚本/ jQuery的-1.2.6.js)%>中类型=文/ JavaScript的>< / SCRIPT>
我有一些方法来添加脚本引用一个AppHelper类:
公共静态字符串ReferenceScript(字符串脚本文件)
{
VAR文件路径= VirtualPathUtility.ToAbsolute(〜/脚本/+脚本文件);
返回<脚本类型= \文/ JavaScript的\SRC = \+文件路径+\>< / SCRIPT>中;
}
所以在你的主页,你可以使用:
<%= AppHelper.ReferenceScript(jQuery的-1.2.6.js)%>
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>
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?
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>
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屋!