如何在kendo ui grid中隐藏一行

时间:2015-07-13 09:22:38

标签: javascript jquery kendo-grid

@{
    ViewBag.Title = " Grid with Multicolumn headers";
}

@using Kendo.Mvc.UI
@using SampleUIApp.Areas.GridSample.Models
@model SampleUIApp.Areas.GridSample.Models.GridSampleModel
@{
    ViewBag.Title = "Grid Sample - InLine Edit";
    Layout = "~/Views/Shared/_PageLayout.cshtml";
}

@section pageBody {


                   <div style="float:right;margin-right:10px;margin-top:10px;margin-bottom:10px">

                    @(Html.Kendo().Button()
                    .Name("Hide_toolbar")
                    .Events(e => e.Click("Hidetoolbar"))
                    .Content("Hide Toolbar"))

                       @(Html.Kendo().Button()
                    .Name("Show_toolbar")
                    .Events(e => e.Click("Showtoolbar"))
                    .Content("Show Toolbar"))

                    </div>
    <br />
    <br />

    @using (Html.BeginForm("InLineIndex", "GridSample", FormMethod.Post, new { @id = "InLineIndexMain" }))
    {


        <div id="DetailPanel" class="containerDiv100">
            @(Html.Kendo().Grid<GridSampleModel>()

                .Name("KendoGrid1")  // Grid Name can be used in Javascript, if required.

                //Columns defination of the fields.
                .Columns(columns =>
                {
                    columns.Template(m => m.SampleId).Title("<input id='checkAll', type='checkbox', class='check-box' />");
                    columns.Group(group=>group
                        .Title("Personal Information")
                        .Columns(info => {
                            info.Bound(m => m.SampleName).Title("Sample Name").Width(200).Filterable(true).HtmlAttributes(new { @style = "font-size:x-small" });
                            info.Bound(m => m.Age).Title("Age").Width(100).Filterable(false).Format("{0:d}").HtmlAttributes(new { @style = "text-align:right" });
                            info.Bound(m => m.Height).Title("Height").Width(150).Locked().Filterable(false).Format("{0:N2}").HtmlAttributes(new { @style = "font-size:x-small" });
                            info.Bound(m => m.City).Title("City (Auto Complete)").Width(350).Lockable(false).Filterable(true).ClientTemplate("#=City.CityName#");

                        })
                    );

                    //columns.Bound(m => m.Age).Title("Age").Width(100).Filterable(false).Format("{0:d}").HtmlAttributes(new { @style = "text-align:right" });
                    //columns.Bound(m => m.Height).Title("Height").Width(150).Locked().Filterable(false).Format("{0:N2}").HtmlAttributes(new { @style = "font-size:x-small" });
                    //columns.Bound(m => m.City).Title("City (Auto Complete)").Width(350).Lockable(false).Filterable(true).ClientTemplate("#=City.CityName#");

                    columns.Bound(m => m.Category).Title("Category (Drop Down List)").Width(400).Filterable(true).ClientTemplate("#=Category.CategoryName#");
                    columns.Bound(m => m.EmployeeList).Title("Employee (Multi Select)").Width(300).Filterable(true).ClientTemplate("#= renderSelectedEmployees(data.EmployeeList)#")
                        .EditorTemplateName("ClientEmployee");


                    columns.Bound(m => m.EntityStatus).Title("Status (CheckBox)").Width(200);

                    columns.Bound(m => m.CreditCard).Title("Credit Card No (Masked TextBox)").Width(250).HtmlAttributes(new { @Style = "font-size:x-small" });
                    columns.Bound(m => m.StartDate).Title("Start Date ").Width(150).Filterable(false).Format("{0:dd/MM/yyyy}").HtmlAttributes(new { @style = "font-size:x-small" });
                    columns.Bound(m => m.EndDate).Title("End Date").Width(150).Filterable(false).Format("{0:dd/MM/yyyy}").HtmlAttributes(new { @style = "font-size:x-small" });
                    columns.Bound(m => m.Qty).Title("Quantity").Width(100).ClientTemplate("#=Qty#").HtmlAttributes(new { @Style = "text-align:right" });
                    columns.Bound(m => m.Rate).Title("Rate").Width(100).ClientTemplate("#=Rate#").Format("{0:N2}").HtmlAttributes(new { @Style = "text-align:right" });

                    columns.Bound(m => m.LineValue).Title("Value").Width(100).Format("{0:n2}").HtmlAttributes(new { @Style = "text-align:right;" });


                    columns.Command(commands =>
                    {
                        commands.Edit().Text(" ");
                        commands.Destroy().Text(" ");
                        commands.Custom("Hide").Click("Hide").HtmlAttributes(new { @style = "min-width : 0;font-size:x-small;" });
                    }).Title("Commands").Width(200).HtmlAttributes(new { @style = "font-size:x-small" });
                })
                .ToolBar(toolbar =>
                {
                    toolbar.Custom().Text("Add New Sample").Name("add").HtmlAttributes(new { @class = "Toolbar_right" }).HtmlAttributes(new { @style = "font-size:x-small" }).Url("~/GridSample/GridSample02/Create");

                    toolbar.Create().HtmlAttributes(new { @class = "Toolbar_right" }).HtmlAttributes(new { @class = "hide-button" });
                })

                .Editable(editable => editable.Enabled(@Model.EditEnable).Mode(GridEditMode.InLine))  // will make grid editable with all cells
            // Here "Enabled(@Model.EditEnable)" will allow user to edit the grid control or not depending on Model's EditEnable value i.e. True / False

                .Pageable()  // Display grid data in multiple pages depending on PageSize parameter
                .Scrollable(config => config.Enabled(true)) // Make grid Scrollable
                .Filterable(config => config.Mode(GridFilterMode.Menu)) // Allow to set filters on different columns of the grid
                .Sortable() // Allow user to sort the data in grid
                .ColumnMenu() // Display menu with different actions on

                // Display grid row in different colour it will be helpful to identify which grid row is selected.
                .Selectable(selectable => selectable
                .Mode(GridSelectionMode.Multiple)
                .Type(GridSelectionType.Row))

                .Navigatable()
                .Resizable(config => { config.Columns(true); })
                .Reorderable(config => { config.Columns(true); })
                .Events(events => events.Save("OnCellDataModified").Edit("OnCellChange")) // Grid events to call javascripts on different actions.
                .DataSource(source => source
                    .Ajax()
                    .Batch(false)
                    .PageSize(5)
                    .ServerOperation(false)
                    .Model(model =>
                    {
                        model.Id(m => m.SampleId);
                        model.Field(m => m.Category).DefaultValue(
                            ViewData["defaultCategory"] as CategoryViewModel);
                        model.Field(m => m.City).DefaultValue(
                            ViewData["defaultCity"] as CityViewModel);

                        //Given below code will not allow user
                        //to change (either manual / calculated) the given cell value
                        //But it will also do not change updated value in model

                        //model.Field(m => m.LineValue).Editable(false);
                    })
                    // Actions called from controller
                    .Read(read => read.Action("Fetch", "GridSample", new { area = "GridSample" }))
                    .Create(create => create.Action("InLine_Insert", "GridSample", new { area = "GridSample" }))
                    .Update(update => update.Action("InLine_Update", "GridSample", new { area = "GridSample" }))
                    .Destroy(delete => delete.Action("Delete", "GridSample", new { area = "GridSample" }))

                    )
            )

        </div>

        <script type="text/javascript">
            // Code added for Keyboard Navigation Support
            $(document.body).keydown(function (e) {
                if (e.altKey && e.keyCode == 87) {
                    $("#grid").data("kendoGrid").table.focus();
                }

            });

            function OnSelectEmply(e) {
                // This sample javascript function called from Employee MultiSelect Partial View
            }

            function CalculateTotValue(data) {
                return data.Qty * data.Rate;
            }

            function OnCellChange(e) {
                //alert("Cell Change");

                //Disable the edit mode depending on the model value of EntityStatus field i.e. True / False
                $("#LineValue").prop("disabled", e.model.EntityStatus);

                //Set Default values while adding new row in Grid
                if (e.model.isNew() && !e.model.dirty) {
                    e.container
                        .find("input[name=SampleName]") // get the input element for the field
                        .val("Sample Name - 4") // set the value

                        .change();   // trigger change in order to notify the model binding
                }
            }

            function OnCellDataModified(e) {
                //alert("Cell Data Modified");

                if (e.values && e.values.LineValue) {
                    //alert("Calculate # LineValue");
                    var qty = e.values.Qty || e.model.Qty;
                    var rate = e.values.Rate || e.model.Rate;
                    e.model.set("LineValue", rate * qty);
                    e.values.set("LineValue", rate * qty);

                    $("#KendoGrid1").data("kendoGrid").refresh();
                }
                else {
                    if (e.values && (e.values.Qty || e.values.Rate)) {
                        //alert("Calculate # Qty, Rate");
                        var qty = e.values.Qty || e.model.Qty;
                        var rate = e.values.Rate || e.model.Rate;
                        e.model.set("LineValue", rate * qty);
                        e.values.set("LineValue", rate * qty);

                        $("#KendoGrid1").data("kendoGrid").refresh();

                    }
                }
            }

            function renderSelectedEmployees(List) {
                //alert(List.length);
                if (List != undefined && List[0] != undefined) {
                    var text;
                    $.each(List, function (index) {
                        if (text == undefined)
                            text = List[index].EmployeeName;
                        else
                            text = text + ", " + List[index].EmployeeName;
                    })

                    //alert($("#LineValue").width);
                    if (text.length > 30) {
                        text = text.substring(0, 5) + " .... (" + List.length.toString().trim() + ")"
                    }
                    return text;
                }
                else
                    return "";
            }
            function Hide(e)
            {

                var grid = $("#KendoGrid1").data("kendoGrid");
                ////e.preventDefault();
                //var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
                //var row = $(this).closest("tr");
                //var rowIdx = $("tr", grid.tbody).index(row);

                //grid.tbody.find("tr:first").hide(); 
                grid.tbody.closest("tr").Hide();
                //grid.tbody.closest("tr").hide();

                //var item = this.dataSource.get(); //Get by ID or any other preferred method
                //this.tbody.find("tr[data-uid='" + item.uid + "']").hide();


            }
            function Hidetoolbar() {



                $(".k-grid-add").hide();

            }
            function Showtoolbar() {



                $(".k-grid-add").show();

            }
            $("#kendoGrid1").on("click", ".hide-button", function () {
                alert("reached");
                $(this).parent().parent().hide();
            });
        </script>
    }
}

正如你所看到的,我的网格中有自定义命令按钮知道隐藏..我希望在单击该按钮时隐藏行。 我怎么做帽子? 我试过一行作为grid.tbody.find(&#34; tr:first&#34;)。hide(); 但这只适用于第一行。我应该为其他行做什么?

2 个答案:

答案 0 :(得分:0)

您的选择器只会找到第一个tr,因此只会找到第一行。

您需要将您的选择更改为:

 grid.tbody.closest("tr").hide();

答案 1 :(得分:0)

这段代码非常难看:

commands.Custom("Hide").Click("Hide").HtmlAttributes(new { @style = "min-width : 0;font-size:x-small;" });

它将服务器端代码与css和javascript混合使用。忘记click事件,不要给它样式属性。你应该给它一个类属性。我们将其命名为hide-button

为CSS中的隐藏按钮元素定义规则,如下所示:

.hide-button {
    min-width: 0;
    font-size: x-small;
}

确保在您的网页中加载此CSS规则。

然后,应该定义您的Javascript。由于您没有向我们提供生成代码的HTML,我将假设您的HTML包含一个网格,其中包含一个tbody,其中包含tr元素,其中包含td元素。其中一个td元素将在每行中包含hide-button。因此,您应该定义此行为:

$("body").on("click", ".hide-button", function() {
    $(this).parent().parent().hide();
});

请注意,由于您没有给我足够的信息,我在答案中使用了假设。因此,如果我的任何假设是错误的,那么答案对你不起作用。如果您还有其他问题,请确保向我提供所有信息。