Razor Nested WebGrid

Excuse the verbose data setup but this works…

@{
    var data = Enumerable.Range(0, 10).Select(i => new { Index = i, SubItems = new object[] { new { A = "A" + i, B = "B" + (i * i) } } }).ToArray();
    WebGrid topGrid = new WebGrid(data);
}

@topGrid.GetHtml(columns:
    topGrid.Columns(
        topGrid.Column("Index"),
        topGrid.Column("SubItems", format: (item) =>
        {
            WebGrid subGrid = subGrid = new WebGrid(item.SubItems);
            return subGrid.GetHtml(
                    columns: subGrid.Columns(
                        subGrid.Column("A"),
                        subGrid.Column("B")
                    )
                );
        })
    )
)

Renders:
No styling

Of course you’ll have to make sure in the GetHtml() method calls you give each grid (both top and sub) unique parameter names for paging/sorting or you’ll end up with conflicts.

Leave a Comment