crgolden
crgolden

Reputation: 4634

Custom row/checkbox template for Kendo UI grid

I am trying to create a custom row template for a Kendo UI grid that includes the checkbox functionality. I have the grid created like this:

@(Html.Kendo().Grid(Model.Users)
              .Name("usersGrid")
              .Columns(columns =>
              {
                  columns.Select().Width(50);
                  columns.Bound(c => c.UserName);
              })
              .DataSource(dataSource => dataSource
                  .Ajax()
                  .ServerOperation(false))
              .ClientRowTemplate(UsersClientTemplate))

With a function to generate the row template like this:

Func<Grid<User>, string> UsersClientTemplate = (grid) =>
{
    var id = Guid.NewGuid();
    return @"<tr data-uid='#:uid#' role='row'>" +
           "<td role='gridcell'>" +
           $"<input class='k-checkbox' data-role='checkbox' type='checkbox' id={id}>" +
           $"<label class='k-checkbox-label k-no-text' for={id}>​</label>" +
           "</td>" +
           "<td role='gridcell'>" +
           "<a href='/users/details/#:data.Id#'>#:data.UserName#</a>" +
           "</td>" +
           "</tr>";
};

The problem is I can't figure out how to generate the unique ids for each row's template. If I don't include the id attribute on the checkbox input element and the for attribute on the checkbox label element, the checkbox/row selection doesn't work. But with the function I have above, the same id is generated for every row template and then the checkbox/row selection only works for the first row, obviously.

What is a better way to do this?

Upvotes: 0

Views: 1335

Answers (1)

Steve Greene
Steve Greene

Reputation: 12304

Templates are generated when the grid is built so as you have seen the id is always the same. What you want is to databind so kendo replaces the id with each record. I use my entity key with a prefix like "cb_" for checkbox:

       $"<input class='k-checkbox' data-role='checkbox' type='checkbox' id='cb_#:uid#'>" +
       $"<label class='k-checkbox-label k-no-text' for='cb_#:uid#'>​</label>" +

Upvotes: 1

Related Questions