我正在使用 Telerik MVC Grid 。我想知道当用户选中/取消选中一个复选框并在页面更改时保持该行时,如何选择/取消选择一行。以下是我所拥有的。请注意我没有使用Kendo Grid,因为这里是我想要的链接:Kendo Example
@(Html.Kendo().Grid<TrialProductViewModel>().Name("products")
.Columns(columns =>
{
columns.Bound(c => c.Selected).ClientTemplate("<input type='checkbox' onclick='editCurrentCell(this)' name='Selected' #= Selected? checked='checked' : '' # />")
columns.Bound(c => c.ProductType).Hidden();
columns.Bound(c => c.Quantity).Filterable
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Selectable(selectable =>
{
selectable.Mode(GridSelectionMode.Multiple);
selectable.Type(GridSelectionType.Row);
selectable.Enabled(false);
})
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(p => p.ItemDescription);
})
.Read(read => read.Action("Products_Read", "Trial")))
.Events(e => e.DataBound("onDataBound"))
)
<script>
function editCurrentCell(element) {
$("#products").data("kendoGrid").one("edit", function (e) {
var row = $(this).closest("tr");
if (e.model.Selected) {
//-remove selection
row.removeClass("k-state-selected");
e.model.set("Selected", false);
}
else {
//-select the row
row.addClass("k-state-selected");
e.model.set("Selected", true);
}
//For testing purpose only
console.log(e.model.Selected);
});
$("#products").data("kendoGrid").editCell($(element).closest("td"));
}
// this will select any rows where the checkbox is checked on data bound event
function onDataBound(e) {
var grid = this;
var currentRecords = grid.dataSource.view();
for (var i = 0; i < currentRecords.length; i++) {
//currentRecords[i] is the current dataItem
if (currentRecords[i].Selected) {
grid.tbody.find("tr[data-uid='" + currentRecords[i].uid + "']").addClass("k-state-selected");
}
}
}
// this allows for selecting multiple rows without having to hold down the ctrl key
// also note in order for this to work you need to set selectable.Enabled(false);
$("#products").delegate('tbody>tr', 'click', function () {
$(this).toggleClass('k-state-selected');
});
答案 0 :(得分:0)
检查复选框的状态,然后相应地设置类
$("#gridName").on("click", ".checkbox", function () {
var checked = this.checked,
row = $(this).closest("tr"),
grid = $("#gridName").data("kendoGrid"),
dataItem = grid.dataItem(row);
checkItems[dataItem.id] = checked;
if (checked) {
$("tr[data-tableId='" + $(row).data("tableId") + "']").addClass("k-state-selected");
}
else {
$("tr[data-tableId='" + $(row).data("tableId") + "']").removeClass("k-state-selected");
}
});