简体   繁体   中英

Disable command by data condition in kendogrid

How can I disable the Delete Button on a row by a given boolean?

Given this example Model:

public class Example
{
    public bool CanDeleted {get; set;} //Delete Button only if true
    //...        
}

KendoGrid<Example> :

columns.Command(c => c.Destroy()); //I want something something like m => m.CanDeleted

Thanks to @Eldho, who has pointed me to the right solution

Javascript:

function onDataBound() {
    var grid = $("#GridID").data("kendoGrid"); //Set GridID
    var gridData = grid.dataSource.view();
    for (var i = 0; i < gridData.length; i++) {
        var gridItem = gridData[i];
        if (!gridItem.CanBeDeleted) { //Condition
            grid.table.find("tr[data-uid='" + gridItem.uid + "']").find(".k-grid-delete").hide(); //Remove button
        }

        //Second Iteration, if we have grouped columns
        if (gridItem.items) {
            for (var j = 0; j < gridItem.items.length; j++) {
                var gridSubItem = gridItem.items[j];
                if (!gridSubItem.CanBeDeleted) { //Condtion
                    grid.table.find("tr[data-uid='" + gridSubItem.uid + "']").find(".k-grid-delete").hide(); //Remove button
                }
            }
        }
    }
}

KendoGrid Helper :

.Events(e => e.DataBound("onDataBound"))

Look at my other answer for a better solution.

After reviewing the situation with a little bit more knowledge about MVC, I found a signficant better solution, using a Extension Method:

public static class KendoExtensions
{
    public static GridTemplateColumnBuilder<TModel> DestroyConditional<TModel>(this GridColumnFactory<TModel> factory, Expression<Func<TModel, bool>> expression)
        where TModel : class
    {
        var template = "# if (" + ExpressionHelper.GetExpressionText(expression) +") { # <a class=\"k-button k-button-icontext k-grid-delete\"><span class=\"k-icon k-delete\"></span>" + TextStrings.Delete + "</a># } #";

        return factory.Template(e => "").ClientTemplate(template).Title("");
    }
}

Feel free to replace TextStrings.Delete to whatever you feel good. Its simple my T4 Localization Logic.

Now in your grid definition it's realy just:

.Columns(columns =>
{
    columns.DestroyConditional(c => c.CanBeDeleted).Width(120);
}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM