簡體   English   中英

如何在Kendo UI網格中隱藏行

[英]How to hide a row in kendo ui 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(“ tr:first”)。hide(); 但這僅適用於第一行。 我應該為其他行做什么?

您的選擇器只會找到第一行tr ,因此只會找到第一行。

您需要將您的選擇更改為:

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

這段代碼非常難看:

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

它將服務器端代碼與CSS和javascript混合在一起。 忘記單擊事件,不要給它樣式屬性。 您應該給它一個類屬性。 讓我們將其命名為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();
});

請注意,由於您沒有給我足夠的信息,因此我在回答中使用了假設。 結果,如果我的任何假設是錯誤的,答案將對您不起作用。 如果您還有其他問題,請確保將所有信息提供給我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM