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

Using Radio Buttons as Foreign Key Editor in the Grid

Environment

ProductTelerik UI for ASP.NET Core Grid
Product Version2019.1.220

Description

I was wondering if there is a way to convert the foreign key column from a dropdown to radio buttons?

Solution

  • Define a new editor in Shared/EditorTemplates and pass the collection via the EditorViewData to it:
Razor
	columns.ForeignKey(x => x.NameCodeId, (System.Collections.IEnumerable)ViewData["NameCodes"], "Id", "Description")
        .Title("Foreign Key Column")
        .Width(200)
        .EditorTemplateName("Radios")
        .EditorViewData((System.Collections.IEnumerable)ViewData["NameCodes"]);
  • Get the ViewData, loop over it, creating the radio checkboxes. The must have a unique name which is translated to their id

    Radios demo

    The name HTML attribute is necessary so that the radios work as a group:

cshtml
    // Radios.cshtml
 
    @model object
    @using ForeignKey.Models
    @{
        var options = (List<NameCode>)ViewData["NameCodes"];
    
        for (var i=0;i <options.Count; i++)
        {
            @Html.Kendo().RadioButton().Name("radio" + options[i].Id.ToString()).Label(options[i].  Description).HtmlAttributes(new { @name = "NameCodeId" }).Value(options[i].Id)
        }
    }
  • In the case of in cell editing, every time you click on the edit cell, it closes. So you need to also add a mouse-down handler targeting the label as the input element is hidden:
Razor
	$(document).ready(function () {
        $("#grid").on("mousedown", ".k-radio-label", function (e) {
            e.preventDefault();
        })
    });

More ASP.NET Core Grid Resources

See Also