New to Telerik UI for ASP.NET Core? Download free 30-day trial

Implementing a Dynamic ComboBox in the Grid

Environment

Product Grid for Progress® Telerik® UI for ASP.NET MVC
Product ComboBox for Progress® Telerik® UI for ASP.NET MVC

Description

I have a Grid where one of the columns requires a ComboBox editor template. What the ComboBox will be populated with, however, depends on a property of the item that generated the Grid. Is there a way to pass this property to the editor template and then have it dynamically bind to the correct list based on the passed in property?

Solution

The desired behavior can be accomplished by using:

  • A separate data source for the Kendo UI ComboBox with a Read action and Data():
    @model int

    @(Html.Kendo().DropDownList()
       .Name("ContentId")
       .DataValueField("ContentId")
       .DataTextField("CreatedBy")
       .DataSource(dataSource =>
       {
           dataSource.Read(read =>
           {
               read.Action("GetList", "Home").Data("getContentId");
           });
       })
    )
  • The getContentId is a JavaScript function, you can place in the view where the Kendo UI Grid is located in a script tag. It obtains the currently edited item and passes it to the read action of the editor as additional data:
    <script>
        function getContentId() {
            var row = $(".k-grid-save-command").closest("tr");
            var grid = $(".k-grid-save-command").closest("[data-role=grid]").data("kendoGrid");
            var dataItem = grid.dataItem(row);
            return { ContentId: dataItem.ContentId }
        }
    </script>
  • Finally, the read action method can look something like this:
    public ActionResult GetList(int? ContentId)
    {
        if (ContentId != null && ContentId == 1)
        {
            var res = new List<ContentAssignment>()
            {
                new ContentAssignment(){ ContentAssignmentId = 1, ContentId = 1, CreatedBy = "One"},
                new ContentAssignment(){ ContentAssignmentId = 2, ContentId = 2, CreatedBy = "Two"}
            };
            return Json(res, JsonRequestBehavior.AllowGet);
        }
        else
        {
            var res = new List<ContentAssignment>()
            {
                new ContentAssignment(){ ContentAssignmentId = 2, ContentId = 2, CreatedBy = "Two"}
            };
            return Json(res, JsonRequestBehavior.AllowGet);
        }
    }

More ASP.NET Core Grid Resources

See Also

In this article