也说 ASP.NET MVC的 Script 管理
WebForm下的ScriptManager在ASP.NET MVC下自然是不能使用的。于是很多人开始困惑如何管理页面上可能发生冲突的脚本。CodePlex上还有一个项目专门做这件事情,当然也有人简单地通过HtmlHelper来解决。如果你看过jQuery UI Extensions for ASP.NET MVC,或者是jQuery Grid for ASP.NET MVC,你还会找到更多的解决方案。总体上讲,这些解决方案的特点是:
1.用一个词典管理已经注册的脚本项,最后再一次性生成所有注册的脚本。所以,你不能漏了在masterpage的bady的最后运行脚本生成。
2.脚本在页面的body区而不是head区。
思考半天,感觉复杂了一点。我的解决方案比较简单,每次注册脚本调用一个扩展足够了。

{
private const string ScriptFormat = "\t<script src=\"{0}\" type=\"text/javascript\"></script>";
private const string CSSFormat = "\t<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\"></link>";
private static string IncludeHeader(HtmlHelper helper, string key, string path, string format)
{
var context = helper.ViewContext.HttpContext;
var exists = context.Items.Contains(key);
if (!exists)
{
var url = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection);
context.Items[key] = true;
return string.Format(format, url.Content(path));
}
return null;
}
public static string IncludeScript(this HtmlHelper helper, string path)
{
return IncludeScript(helper, path.ToLower(), path);
}
public static string IncludeScript(this HtmlHelper helper, string key, string path)
{
return IncludeHeader(helper, key, path, ScriptFormat);
}
public static string IncludeCSS(this HtmlHelper helper, string path)
{
return IncludeCSS(helper, path.ToLower(), path);
}
public static string IncludeCSS(this HtmlHelper helper, string key, string path)
{
return IncludeHeader(helper, key, path, CSSFormat);
}
}
使用的时候在masterPage的head区域加入一个占位标记:
<asp:ContentPlaceHolder ID="ScriptContent" runat="server" />
然后在每个view中你都可以通过下面的代码来注册脚本了:
<%= Html.IncludeCSS("http://www.cnblogs.com/Content/Site.css") %>
<%= Html.IncludeCSS("http://www.cnblogs.com/Content/ui.jqgrid.css")%>
<%= Html.IncludeCSS("jQuery_Theme", Html.GetThemePath()) %>
<%= Html.IncludeScript("http://www.cnblogs.com/Scripts/jquery-1.3.2.min.js")%>
...
当然,我也有我的困惑。我的困惑就是,为什么Microsoft没有直接提供Script管理解决方案,抑或是已经提供了,我没有发现?
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义