使用编辑器/显示模板中的部分 [英] Using sections in Editor/Display templates
问题描述
我想将我所有的 JavaScript 代码放在一个部分;就在我的主布局页面中关闭 body
标记之前,只是想知道最好的方法是 MVC 风格.
例如,如果我创建一个使用 jQuery UI 的 DateTime Picker 的 DisplayTemplateDateTime.cshtml
文件,那么我会将 JavaScript 直接嵌入到该模板中,但随后它将呈现中间页面.>
在我的普通视图中,我可以只使用 @section JavaScript {//js here }
然后在我的主布局中使用 @RenderSection("JavaScript", false)
但是这似乎不适用于显示/编辑器模板 - 有什么想法吗?
您可以继续使用两个助手的连接:
public static class HtmlExtensions{public static MvcHtmlString Script(this HtmlHelper htmlHelper, Func
然后在您的 _Layout.cshtml
中:
...@Html.RenderScripts()
以及某个模板中的某处:
@Html.Script(@<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>)
I want to keep all of my JavaScript code in one section; just before the closing body
tag in my master layout page and just wondering the best to go about it, MVC style.
For example, if I create a DisplayTemplateDateTime.cshtml
file which uses jQuery UI's DateTime Picker than I would embed the JavaScript directly into that template but then it will render mid-page.
In my normal views I can just use @section JavaScript { //js here }
and then @RenderSection("JavaScript", false)
in my master layout but this doesn't seem to work in display/editor templates - any ideas?
You could proceed with a conjunction of two helpers:
public static class HtmlExtensions
{
public static MvcHtmlString Script(this HtmlHelper htmlHelper, Func<object, HelperResult> template)
{
htmlHelper.ViewContext.HttpContext.Items["_script_" + Guid.NewGuid()] = template;
return MvcHtmlString.Empty;
}
public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
{
foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys)
{
if (key.ToString().StartsWith("_script_"))
{
var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func<object, HelperResult>;
if (template != null)
{
htmlHelper.ViewContext.Writer.Write(template(null));
}
}
}
return MvcHtmlString.Empty;
}
}
and then in your _Layout.cshtml
:
<body>
...
@Html.RenderScripts()
</body>
and somewhere in some template:
@Html.Script(
@<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
)
这篇关于使用编辑器/显示模板中的部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!