Telerik Kendo MVC Grid - 如何使用复选框列设置onload / initial filter等于True?

时间:2015-12-14 18:44:44

标签: asp.net-mvc kendo-ui kendo-grid kendo-asp.net-mvc

我被指控将公司当前的webforms网站页面更改为MVC。我们使用Telerik工具包,我正在寻找一种在网格上设置初始过滤器的方法,以便在加载页面时,网格默认只显示已检查的记录(true)。我发现了几个与此类似的问题,但到目前为止,我在这些实例中找到的答案都没有处理复选框。

以下代码是我的“有效?” = MVC网格中的True / False列。我正在检查每条记录的删除日期,当删除日期存在时,该日期将被视为“已停用”。我的用户启动过滤在网格上工作得很好,但是我无法弄清楚如何将此列上的初始过滤器值设置为TRUE,同时还允许用户清除过滤器,然后查看已停用的记录以及活动记录。 / p>

感谢您提供的任何帮助。如果我实现这个完全错误,请随时告诉我,但请同时提供一个完成此功能的正确方法示例。

columns.Bound("DeleteDateUTC")
     .ClientTemplate("<input type='checkbox' #= kendo.parseDate(DeleteDateUTC) ? '' : checked='checked' # disabled='disabled' />")
     .Title("Active?")
     .Filterable(ftb => ftb.Cell(cell => cell.Operator("Is equal to")))
     .Width(100);

谢谢!

编辑1:

<div id="gridArea" class="k-virtual-scrollable-wrap">
@(Html.Kendo().Grid<dynamic>()
    .Name("OperatorsGrid")
    .Mobile(MobileMode.Auto)
    .Pageable(pager => pager.PageSizes(new int[] { 50, 100, 250 })
                                    .Refresh(true))
    .Sortable()
    .Resizable(resize => resize.Columns(true))
    .HtmlAttributes(new { style = "height: 800px;" })
    .Scrollable()
    .ColumnMenu()
    .Filterable(ftb => ftb.Mode(GridFilterMode.Row))
    .Events(e => e.DataBound("onDataBound").Cancel("onCancel"))
    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model =>
        {
            model.Id("ID");
        })
        .PageSize(100)
        .Read(read => read.Action("Operators_Read", "TableMx"))
    )
    .Columns(columns =>
    {
        columns.Command(cmd => cmd.Custom("Operators_Edit").Text(" ").Click("edit"))
            .Title("Edit")
            .Width(75);
        columns.Command(cmd => cmd.Custom("Operators_Deactivate").Text(" ").Click("deactivate"))
            .Title("Deactivate")
            .Width(100);
        columns.Bound("DeleteDateUTC")
            .ClientTemplate("<input type='checkbox' #= kendo.parseDate(DeleteDateUTC) ? '' : checked='checked' # disabled='disabled' />")
            .Title("Active?")
            .Filterable(ftb => ftb.Cell(cell => cell.Operator("Is equal to")))
            .Width(100);
        columns.Bound("Name")
            .Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")))
            .Title("Name")
            .Width(350);
        columns.Bound("Address")
            .Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")))
            .Title("Address")
            .Width(250);
        columns.Bound("City")
            .Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")))
            .Title("City")
            .Width(150);
        columns.Bound("StateAbbrev")
            .Filterable(ftb => ftb.Cell(cell => cell.ShowOperators(false)))
            .Title("State")
            .Width(100);
        columns.Bound("Zip")
            .Filterable(false)
            .Title("Zip")
            .Width(70);
        columns.Bound("ContactName")
            .Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")))
            .Title("Contact Name")
            .Width(175);
        columns.Bound("ContactEmail")
            .Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")))
            .Title("Email")
            .Width(175);
        columns.Bound("ContactPhone")
            .Filterable(ftb => ftb.Cell(cell => cell.ShowOperators(false)))
            .Title("Phone")
            .Width(150);
        columns.Bound("CreateDateUTC")
            .ClientTemplate("#= kendo.parseDate(CreateDateUTC) ? (kendo.toString(kendo.parseDate(CreateDateUTC), 'MM/dd/yyyy h:mm tt')) : '' #")
            .Title("Create Date UTC")
            .Width(250);
        columns.Bound("CreatedByUser")
            .Title("Created By")
            .Width(150);
        columns.Bound("LastChangeDateUTC")
            .ClientTemplate("#= kendo.parseDate(LastChangeDateUTC) ? (kendo.toString(kendo.parseDate(LastChangeDateUTC), 'MM/dd/yyyy h:mm tt')) : '' #")
            .Title("Last Update Date UTC")
            .Width(250);
        columns.Bound("LastChangedByUser")
            .Title("Last Updated By")
            .Width(150);
        columns.Bound("DeleteDateUTC")
            .ClientTemplate("#= kendo.parseDate(DeleteDateUTC) ? (kendo.toString(kendo.parseDate(DeleteDateUTC), 'MM/dd/yyyy h:mm tt')) : '' #")
            .Title("Deleted Date UTC")
            .Width(250);
        columns.Bound("DeletedByUser")
            .Title("Deleted By")
            .Width(150);
    })                
)

编辑2: 在网格下面添加脚本部分。我不确定这是否是必要的,以帮助我,但看到正在发生的一切都不会有害。

<script>
$(function () {
    var grid = $("#OperatorsGrid").data("kendoGrid");

    //Save personalized settings for this grid (columns shown, etc.)
    $("#save").click(function (e) {
        e.preventDefault();
        localStorage["kendo-grid-options"] = kendo.stringify(grid.getOptions());
    });

    //If the user has saved options, load them.  Otherwise, load the default filter for the active column
    var options = localStorage["kendo-grid-options"];
    if (options) {
        grid.setOptions(JSON.parse(options));
    }
    else {
        grid.dataSource.filter({ field: "Active?", operator: "eq", value: "checked" });
    }

    //Remove column menu from any columns specified by data-title below:
    //grid.thead.find("[data-title=columnTitleHere]>.k-header-column-menu").remove();
    grid.thead.find("[data-title=\"Active?\"]>.k-header-column-menu").remove();
});

function deactivate(e) {
    e.preventDefault();
    var id = this.dataItem($(e.currentTarget).closest("tr")).id;
    var url = "/TableMx/Operators_Deactivate/" + id;
    $.ajax({
        type: "POST",
        url: url,
    })
    .done(function () {
        // refresh the grid to remove the just deactivated order
        refreshGrid();
    })
    .fail(function () { alert("failure deactivating operator") })
}

function edit(e) {        

}

function onDataBound(e) {        
    $(".k-grid-Operators_Deactivate span").addClass("k-icon k-delete ob-icon-only");
    $(".k-grid-Operators_Edit span").addClass("k-icon k-edit ob-icon-only");
}

function onCancel(e) {
    e.preventDefault();
    e.sender.refresh();
}

function refreshGrid() {
    if ($(".k-i-refresh").length > 0) {
        $(".k-i-refresh").trigger('click');
    }
}

1 个答案:

答案 0 :(得分:1)

不使用dynamic模型,而是创建如下视图模型:

public class OperatorViewModel
{
    // I'm not sure if your ID is int or string...
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }

    // All the other properties here
    // ...
    // ...

    [Display(Name = "Active?")]    
    public bool IsActive { get; set; }
}

如您所见,我还在视图模型中添加了IsActive属性。您将在Controller中填充此属性,具体取决于是否存在DeleteDateUTC

然后,您的网格就像(请注意我添加到您的数据源中的.Filter):

@(Html.Kendo().Grid<YourApp.ViewModels.OperatorViewModel>()
    .Name("OperatorsGrid")
    .Mobile(MobileMode.Auto)
    .Pageable(pager => pager.PageSizes(new int[] { 50, 100, 250 })
                                    .Refresh(true))
    .Sortable()
    .Resizable(resize => resize.Columns(true))
    .HtmlAttributes(new { style = "height: 800px;" })
    .Scrollable()
    .ColumnMenu()
    .Filterable(ftb => ftb.Mode(GridFilterMode.Row))
    .Events(e => e.DataBound("onDataBound").Cancel("onCancel"))
    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model =>
        {
            model.Id("ID");
        })
        // THIS IS WHERE YOU FILTER THE IsActive FIELD
        .Filter(f => f.Add(m => m.IsActive.Equals(true)))
        .PageSize(100)
        .Read(read => read.Action("Operators_Read", "TableMx"))
    )
    .Columns(columns =>
    {
        columns.Command(cmd => cmd.Custom("Operators_Edit").Text(" ").Click("edit"))
            .Title("Edit")
            .Width(75);
        columns.Command(cmd => cmd.Custom("Operators_Deactivate").Text(" ").Click("deactivate"))
            .Title("Deactivate")
            .Width(100);
        columns.Bound(c => c.IsActive)
            .ClientTemplate("<input type='checkbox' #= IsActive ? '' : checked='checked' # disabled='disabled' />")
            .Filterable(ftb => ftb.Cell(cell => cell.Operator("Is equal to")))
            .Width(100);
        columns.Bound(c => c.Name)
            .Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")))
            .Width(350);
        columns.Bound(c => c.Address)
            .Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")))
            .Width(250);
        columns.Bound(c => c.City)
            .Filterable(ftb => ftb.Cell(cell => cell.Operator("contains")))
            .Width(150);
        //...
        //...

确保您的Operators_Read操作返回IEnumerable<OperatorViewModel>的JSON。