MVCContrib grid - Can I specify tbody attributes?

I am trying to use the MVCContrib grid with KnockoutJS . For this, I have to specify data binding in tbody, for example. <tbody data-bind="foreach: people"> . I can not find a way to do this.

@Html.Grid(Model).Attributes() applies my binding to the <table> . Is there a way to set the tbody attribute?

+4
source share
1 answer

The short answer is no, there is no way to set attributes in tbody with the current implementation.

But you can implement this functionality yourself:

You just need to implement your own version of mothod RenderBodyStart from the GridRenderer class.

There is an alredy implementation of the GridRenderer called HtmlTableGridRenderer , on which you can build:

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

In your view, instead of calling Render() you can use the RenderUsing method, where you can specify your own renderer:

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

And the generated html will look something like this:

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

It should be noted that this is just a quick and dirty solution to show what is possible, and there are more extension points that you can use to make the attribute more enjoyable.

+2
source

Source: https://habr.com/ru/post/1445050/


All Articles