WebForm下的ScriptManager在ASP.NET MVC下自然是不能使用的。于是很多人开始困惑如何管理页面上可能发生冲突的脚本。CodePlex上还有一个项目专门做这件事情,当然也有人简单地通过HtmlHelper来解决。如果你看过jQuery UI Extensions for ASP.NET MVC,或者是jQuery Grid for ASP.NET MVC,你还会找到更多的解决方案。总体上讲,这些解决方案的特点是:
代码
public static ScriptManagementExtension
{
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>";
{
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;
}
{
return IncludeScript(helper, path.ToLower(), path);
}
{
return IncludeHeader(helper, key, path, ScriptFormat);
}
{
return IncludeCSS(helper, path.ToLower(), path);
}
{
return IncludeHeader(helper, key, path, CSSFormat);
}
}
使用的时候在masterPage的head区域加入一个占位标记:
<asp:ContentPlaceHolder ID="ScriptContent" runat="server" />
<%= 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")%>