New to Telerik UI for ASP.NET MVC? Download free 30-day trial

Conditionally Hide Expand Icons for the Detail Template in the Grid

Environment

Product Telerik UI for ASP.NET MVC Grid
Product Version 2024.1.130

Description

How can I hide the expand icon for the detail template in a Telerik UI for ASP.NET MVC Grid based on a HasChildren value that is defined as Model property?

Solution

  1. Traverse the rows of the parent Grid within the DataBound event.
  2. To retrieve the data item, access the <tr> element by using the dataItem() client-side method of the Grid.
  3. Conditionally hide the icon based on the HasChildren field.
    <script id="template" type="text/kendo-tmpl">
        @(Html.Kendo().Grid(@childData)
            .Name("grid#=Id#")
            .Columns(columns =>
            {
                columns.Bound(p => p.ChildName).Title("Child Name");
            })
            .Pageable()
            .Sortable()
            .Filterable()    
            .DataSource(dataSource => dataSource        
                .Ajax()
                .PageSize(20)
                .ServerOperation(false)        
             )
             .ToClientTemplate()
        )
    </script>

    @(Html.Kendo().Grid(@parentData)
        .Name("grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.ParentName).Title("Parent Name");

        })
        .Events(events => events.DataBound("onDataBound"))
        .Pageable()
        .Sortable()
        .Filterable()    
        .ClientDetailTemplateId("template")
        .DataSource(dataSource => dataSource        
            .Ajax()
            .PageSize(20)
            .ServerOperation(false)        
         )
    )
    public class Parent {
        public int Id {get;set;}
        public string ParentName {get;set;}
        public bool HasChildren {get;set;}
    }
    public class Child {
        public int Id {get;set;}
        public int ParentId {get;set;}
        public string ChildName {get;set;}
    }
    <script>
        function onDataBound(e){
            var items = e.sender.items(); // 1. Gather the DOM element representations of the rows.
            items.each(function(){ // 2. Traverse through each of the rows.
              var dataItem = e.sender.dataItem(row); // 3. Obtain the dataItem counter-part of the row.
              if(!dataItem.HasChildren){ // 4. Assert the for the HasChildren field.
                row.find(".k-hierarchy-cell").html(""); // 5. Hide the expand icon.
              }
            })
        }
    </script> 

For a full implementation of the aforementioned approach, refer to the REPL example on conditionally hiding the expand icon of the Grid's Detail template.

More ASP.NET MVC Grid Resources

See Also

In this article