New to Telerik UI for ASP.NET Core? Start a free 30-day trial
Displaying a Nested Grid in a Grid Column Template
Environment
Product | Telerik UI for ASP.NET Core Grid |
Progress Telerik UI for ASP.NET Core version | Created with the 2024.2.514 version |
Description
How can I display a button in a specified Grid column that toggles a nested Grid?
Solution
Here are the steps for implementation:
-
Integrate a Button and a hidden Grid in the main Grid's column by using the Template component:
Razor@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.OrderViewModel>() .Name("grid") .Columns(columns => { columns.Bound(f => f.Id) .ClientTemplate(Html.Kendo().Template() .AddComponent(x => x .Button() .Name("detailsBtn_${data.Id}") .Content("Expand") .Events(ev => ev.Click("onDetailsClick")) ) .AddHtml("<div class='gridContainer'>") .AddComponent(x => x .Grid<DetailsViewModel>() .Name("detailsGrid_${data.Id}") .AutoBind(false) // Prevent the initial Read request during the Grid's initialization. .Columns(c => { c.Bound(x => x.Id); c.Bound(x => x.Name); }) .Scrollable() .HtmlAttributes(new { style = "height: 200px;"}) .DataSource(dataSource => dataSource .Ajax() .PageSize(20) .Read(read => read.Action("DetailsRead", "Grid")) ) ) .AddHtml("</div>") ); }) // Other configuration. )
-
Hide the
div
element that wraps the Grid declaration:Razor<style> .gridContainer { display: none; } </style>
-
Handle the
click
event of the Expand button and toggle the Grid's container.
Get a reference to the Grid and call the read()
method of its DataSource by passing the Id field to the server to filter the data based on the data item of the current row (the main Grid's row).
Html
function onDetailsClick(e) {
var id = $(e.target).attr("id").split("_")[1];
var btnLabel = $(e.target).find(".k-button-text").html(); // Get the current label of the Button.
if (btnLabel == "Expand") {
$(e.target).find(".k-button-text").html("Collapse");
} else $(e.target).find(".k-button-text").html("Expand");
$(e.target).next().toggle(); // Toggle the visibility of the nested Grid.
var grid = $(`#detailsGrid_${id}`).data("kendoGrid").dataSource.read({ parentId: id });
}