Ответ 1
У меня была такая же проблема поверх дублирующих скриптов, поэтому я создал пару методов расширения:
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());
}
}
На любом View или Partial View или Display/Edit Template вы просто добавляете то, что вам нужно:
@{
Html.AddJavaScript("http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js");
}
В ваших макетах вы окажете его там, где хотите:
<!DOCTYPE html>
<html lang="en">
<head>
@Html.RenderStyles()
@Html.RenderJavascripts()
Единственная проблема, с которой вы можете столкнуться, - это порядок, в котором сценарии отображаются, если вы получаете сложность. Если это становится проблемой, просто добавьте скрипты в нижнюю часть ваших представлений/шаблонов и просто измените порядок в методе расширения перед их рендерингом.