我在重复脚本上遇到了同样的问题,所以我创建了几个扩展方法:
public static class HtmlHelperExtensions
{
private const string _jSViewDataName = "RenderJavaScript";
private const string _styleViewDataName = "RenderStyle";
public static void AddJavaScript(this HtmlHelper htmlHelper,
string scriptURL)
{
List<string> scriptList = htmlHelper.ViewContext.HttpContext
.Items[HtmlHelperExtensions._jSViewDataName] as List<string>;
if (scriptList != null)
{
if (!scriptList.Contains(scriptURL))
{
scriptList.Add(scriptURL);
}
}
else
{
scriptList = new List<string>();
scriptList.Add(scriptURL);
htmlHelper.ViewContext.HttpContext
.Items.Add(HtmlHelperExtensions._jSViewDataName, scriptList);
}
}
public static MvcHtmlString RenderJavaScripts(this HtmlHelper HtmlHelper)
{
StringBuilder result = new StringBuilder();
List<string> scriptList = HtmlHelper.ViewContext.HttpContext
.Items[HtmlHelperExtensions._jSViewDataName] as List<string>;
if (scriptList != null)
{
foreach (string script in scriptList)
{
result.AppendLine(string.Format(
"<script type=\"text/javascript\" src=\"{0}\"></script>",
script));
}
}
return MvcHtmlString.Create(result.ToString());
}
public static void AddStyle(this HtmlHelper htmlHelper, string styleURL)
{
List<string> styleList = htmlHelper.ViewContext.HttpContext
.Items[HtmlHelperExtensions._styleViewDataName] as List<string>;
if (styleList != null)
{
if (!styleList.Contains(styleURL))
{
styleList.Add(styleURL);
}
}
else
{
styleList = new List<string>();
styleList.Add(styleURL);
htmlHelper.ViewContext.HttpContext
.Items.Add(HtmlHelperExtensions._styleViewDataName, styleList);
}
}
public static MvcHtmlString RenderStyles(this HtmlHelper htmlHelper)
{
StringBuilder result = new StringBuilder();
List<string> styleList = htmlHelper.ViewContext.HttpContext
.Items[HtmlHelperExtensions._styleViewDataName] as List<string>;
if (styleList != null)
{
foreach (string script in styleList)
{
result.AppendLine(string.Format(
"<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />",
script));
}
}
return MvcHtmlString.Create(result.ToString());
}
}
在任何视图或部分视图或显示/编辑模板上,您只需添加您需要的内容:
@{
Html.AddJavaScript("http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js");
}
在您的布局中,您可以将它呈现在您想要的位置:
<!DOCTYPE html>
<html lang="en">
<head>
@Html.RenderStyles()
@Html.RenderJavascripts()
如果变得复杂,您可能遇到的唯一问题是脚本的呈现顺序。如果这成为问题,只需将脚本添加到视图/模板的底部,并在渲染它们之前简单地反转扩展方法中的顺序。