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

Filtering and Editing a ForeignKey Column Bound to an Enum Field in Grid

Environment

ProductTelerik UI for ASP.NET Core Grid
Product Version2024.4.1112

Description

How can I bind a Grid to a ForeignKey column and ensure that the names of enum members are displayed in the column's filter menu? Also, how to use a DropDownList editor for the enum field when the Grid enters edit mode?

Solution

When binding a ForeignKey column to an enum Model property, convert the enum members to a SelectListItem data collection.

  • Binding the ForeignKey column to a local collection:

    Razor
        @(Html.Kendo().Grid<GridModel>()
            .Name("grid")
            .Columns(columns =>
            {
                columns.ForeignKey(p => p.Status, (System.Collections.IEnumerable)ViewData["statuses"], "Value", "Text")
                .Filterable(x => x.Extra(false).Operators(operators => operators.ForEnums(str => str.Clear().IsEqualTo("Equals"))));
            })
            ...// Additional configuration.
        )
  • Binding the ForeignKey column to remote data:

    Razor
        @(Html.Kendo().Grid<GridModel>()
            .Name("grid")
            .Columns(columns =>
            {
                columns.ForeignKey(p => p.Status, ds => ds.Read(r => r.Action("ReadStatuses", "Home")), "Value", "Text")
                .Filterable(x => x.Extra(false).Operators(operators => operators.ForEnums(str => str.Clear().IsEqualTo("Equals"))));
            })
            ...// Additional configuration.
        )

When the Grid is InCell or InLine editable, the Grid will look for the default GridForeignKey.cshtml editor template in the ~Views\Shared\EditorTemplates folder, and populate it with the passed data collection through the column declaration:

C#
    @model object
    @(Html.Kendo().DropDownListFor(m => m)
    .BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("")+ "_Data"])
    )

When the Grid is configured for Popup editng, decorate the Model property with the UIHint attribute and add a DropDownList editor to the ~Views\Shared\EditorTemplates folder.

C#
    using System.ComponentModel.DataAnnotations;

    public class GridModel
    {
        [UIHint("EnumEditor")]
        public ShipmentStatus Status { get; set; }
    }

More ASP.NET Core Grid Resources

See Also