Using Radio Buttons as Foreign Key Editor in the Grid
Environment
Product | Telerik UI for ASP.NET MVC Grid |
Product Version | 2019.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 theEditorViewData
to it:
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
The name HTML attribute is necessary so that the radios work as a group:
// 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:
$(document).ready(function () {
$("#grid").on("mousedown", ".k-radio-label", function (e) {
e.preventDefault();
})
});