如约而至
你不能渲染@section's,因为它在被部分视图渲染时不受支持,在此之前你可以做到这一点:
在你的_Layout.cshtml写下
@RenderSection("scripts", false)
@Html.RenderSection("scripts")
第一行是默认,第二行是你全新的渲染部分的方式,我在我的代码中都使用了...
现在让我们添加一些代码到我们的局部视图
而不是
@section scripts {
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}
替换为:
@Html.Section(
@<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>, "scripts"
)
@Html.Section(
@<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>, "scripts"
)
还有我们的小助手,您只需将其放入您的Models 文件夹并在您的部分视图和布局页面中引用它
// using idea from http://stackoverflow.com/questions/5433531/using-sections-in-editor-display-templates/5433722#5433722
public static class HtmlExtensions
{
public static MvcHtmlString Section(this HtmlHelper htmlHelper, Func<object, HelperResult> template, string addToSection)
{
htmlHelper.ViewContext.HttpContext.Items[String.Concat("_", addToSection, "_", Guid.NewGuid())] = template;
return MvcHtmlString.Empty;
}
public static IHtmlString RenderSection(this HtmlHelper htmlHelper, string sectionName)
{
foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys)
{
if (key.ToString().StartsWith(String.Concat("_", sectionName, "_")))
{
var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func<object, HelperResult>;
if (template != null)
{
htmlHelper.ViewContext.Writer.Write(template(null));
}
}
}
return MvcHtmlString.Empty;
}
}
要呈现 CSS,您只需要使用其他部分名称,例如:
在_Layout.cshtml
@Html.RenderSection("styles")
在您的部分视图中
@Html.Section(
@<link rel="stylesheet" href="http://twitter.github.com/bootstrap/1.3.0/bootstrap.min.css">, "styles"
)
我希望这会有所帮助。