New to Telerik UI for ASP.NET MVCStart a free 30-day trial

Use GroupHeaderTemplate in the ForeignKey Column of a Grid

Environment

ProductTelerik UI for ASP.NET MVC Grid
Product version2025.1.227

Description

How can I modify the default group header of the ForeignKey Grid column?

Solution

You can achieve this requirement using the following implementation:

  1. Create a groupable Grid and define a ForeignKey column with ClientGroupHeaderTemplate option:

    Razor
    @(Html.Kendo().Grid<Telerik.Examples.Mvc.Areas.GridForeignKeyGroupHeaderTemplate.Models.Order>()
        .Name("Grid")
        .Columns(columns => {
            columns.Bound(p => p.OrderID);
            columns.ForeignKey(p => p.EmployeeId, (System.Collections.IEnumerable)ViewData["employees"], "EmployeeId", "Name")
                .ClientGroupHeaderTemplate("#= values[value] #");
            columns.Bound(p => p.OrderDescription);
            columns.Bound(p => p.OrderDate);
        })
        .Groupable()
        ... // Additional configuration options.
        .DataSource(dataSource => dataSource
            .Ajax()
            .Batch(true)
            .ServerOperation(false)
            .Model(model => {
                model.Id(p => p.OrderID);
                model.Field(p => p.OrderID).Editable(false);
            })
            .Read(read => read.Action("ForeignKeyColumn_Read", "Home"))
            .Update(update => update.Action("ForeignKeyColumn_Update", "Home"))
        )
    )
  2. When the page with the Grid is loaded, get a reference to the Grid, access the data of the ForeignKey column, and populate the values object that is referenced in the ClientGroupHeaderTemplate option:

    JS
    var values = {};
    
    $(function () {
        var grid = $("#Grid").data("kendoGrid");
        var fieldName = "EmployeeId";
        var columns = grid.columns;
        var columnIndex = getColumnIndex(fieldName, columns);
        var foreignData = columns[columnIndex].values;
        for (var i = 0; i < foreignData.length; i++) {
            values[foreignData[i].value] = foreignData[i].text;
        }
    });
    
    function getColumnIndex(fieldName, columns) {
        for (var i = 0; i < columns.length; i++) {
            if (columns[i].field === fieldName) {
                return i;
            }
        }
    }

To review the complete example, refer to the project on how to use the GroupHeaderTemplate option in a `ForeignKey column configuration when using the Grid in ASP.NET MVC applications.

More ASP.NET MVC Grid Resources

See Also