【问题标题】:MVCContrib grid - Can I specify tbody attributes?MVCContrib 网格 - 我可以指定 tbody 属性吗?
【发布时间】:2012-10-29 19:13:12
【问题描述】:

我正在尝试将 MVCContrib 网格与 KnockoutJS 一起使用。为此,我必须在 tbody 中指定数据绑定,例如<tbody data-bind="foreach: people">。我找不到如何做到这一点的方法。

@Html.Grid(Model).Attributes() 将我的绑定应用于<table> 标签。有没有办法设置tbody 属性?

【问题讨论】:

    标签: knockout.js mvccontrib mvccontrib-grid


    【解决方案1】:

    简短的回答是不,目前的实现无法在tbody上设置属性

    但是你可以自己实现这个功能:

    您只需要从GridRenderer 类中实现您自己版本的RenderBodyStart 方法。

    已经有一个名为 HtmlTableGridRendererGridRenderer 实现,您可以在此基础上进行构建:

    public class BodyWithAttributesHtmlTableGridRenderer<T> 
        : HtmlTableGridRenderer<T> where T : class
        {
            private readonly IDictionary<string, object> bodyAttributes;
    
            public BodyWithAttributesHtmlTableGridRenderer(
                IDictionary<string, object> bodyAttributes)
            {
                this.bodyAttributes = bodyAttributes;
            }
    
            protected override void RenderBodyStart()
            {
                string str = BuildHtmlAttributes(bodyAttributes);
                if (str.Length > 0)
                    str = " " + str;
                RenderText(string.Format("<tbody{0}>", str));
            }
        }
    

    在您看来,您可以使用RenderUsing 方法来指定您的自定义渲染器,而不是调用Render()

    @Html.Grid(Model))
        .RenderUsing(new BodyWithAttributesHtmlTableGridRenderer<MyModel>(
        new Dictionary<string, object>(){{"data-bind", "foreach: people"}}))
    

    生成的 html 看起来像这样:

    <table class="grid">
        <thead>
            <tr>
                <th>Prop</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: people">
            <tr class="gridrow">
                <td>1</td>
            </tr>
            <tr class="gridrow_alternate">
                <td>2</td>
            </tr>
        </tbody>
    </table>
    

    您应该注意,这只是一个快速而肮脏的解决方案,以展示可能的情况,并且您可以使用更多扩展点来使属性传递更好。

    【讨论】:

    猜你喜欢
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 2012-10-14
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多