在编辑/显示模板使用节 [英] Using sections in Editor/Display templates

查看:79
本文介绍了在编辑/显示模板使用节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保持在一个部分我的JavaScript code的;刚刚结束正文之前标记在我的主人布局页和只是想知道最好的去了解它,MVC的风格。

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.

例如,如果我创建一个使用jQuery UI的日期时间选择器比我会直接嵌入JavaScript的成模板的 DisplayTemplate \\ DateTime.cshtml 文件,但它将呈现网页中部。

For example, if I create a DisplayTemplate\DateTime.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.

在我正常的意见,我可以只使用 @section的JavaScript {//这里的js} 然后 @RenderSection(JavaScript的,FALSE) 在我的总纲发展蓝图,但这似乎并没有显示在工作/编辑模板 - 任何想法

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;
    }
}

,然后在 _Layout.cshtml

<body>
...
@Html.RenderScripts()
</body>

和地方一些模板:

@Html.Script(
    @<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
)

这篇关于在编辑/显示模板使用节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆