Reputation: 15350
I am trying to use the kendo ui mvc wrapper grid to bind to a list of objects.
In addition, I'm adding a checkbox to the first column of each row and the grid is wrapper in a form. I then want to take advantage of the default model binding for a (sequential or non-sequential) list when submitting.
The problem I am having is writing the HiddenFor and CheckBoxFor helper methods that are indexed.
If I was to write the table layout myself it would be something like this:
<table>
<tbody>
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
<input type="hidden" name="Index" autocomplete="off" value="@i" />
@Html.HiddenFor(m => Model[i].Id)
@Html.CheckBoxFor(m => Model[i].Selected)
</td>
...
This produces the below HTML output.
<input type="hidden" name="Index" autocomplete="off" value="0" />
<input id="[0].Id" name="[0].Id" type="hidden" value="1234" />
<input id="[0].Selected" name="[0].Selected" type="checkbox" value="true" />
<input name="[0].Selected" type="hidden" value="false" />
How is this possible with Server side binding using the kendo ui mvc grid wrapper?
I tried using a counter defined outside the grid and incrementing it both on .RowAction and inside the bound column but had mixed results which did not give me the desired result.
var counter = 0;
@(Html.Kendo().Grid(Model)
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Id)
.Template(
@<text>
<input type="hidden" name="Index" autocomplete="off" value="@counter" />
@Html.HiddenFor(m => Model[counter].Id)
@Html.CheckBoxFor(m => Model[counter].Selected)
</text>)
...
The problem I had was increment the counter. Maybe there is a better solution?
Another attempt I made was to write the table html myself and then apply the javascript grid binding $("grid").kendoGrid(...). However, I then loose the ability of defining css classes on my tr/td elements dynamically.
Upvotes: 2
Views: 8109
Reputation: 1038720
Try like this (untested):
var counter = -1;
@(Html.Kendo().Grid(Model)
.Name("grid")
.Columns(columns =>
{
columns
.Bound(c => c.Id)
.Template(
@<text>
@{counter++;}
<input type="hidden" name="Index" autocomplete="off" value="@counter" />
@Html.HiddenFor(m => m[counter].Id)
@Html.CheckBoxFor(m => m[counter].Selected)
</text>);
... some other columns
}
)
Upvotes: 3