How to make a string data type column as checkbox in Kendo Grid?

810 views Asked by At

I have a string field IsEnabled, it’s string. Value can be Yes, No or null. I am binding this column to grid column. It’s working as expected. But I want to show this on UI as checkbox. For value Yes, it should be checked or No or null it should be unchecked. And user can check/uncheck, based on user’s action. Yes or NO will be inserted in database.

I couldn’t find proper way of doing this, so what is the best way to handle this scenario?

I have tried by by adding one more bool field and setting it based on value Yes, No or null. And binding this field to grid.

But I am looking for a clean approach

2

There are 2 answers

0
Vivek Nuna On BEST ANSWER

As I was looking for a Kendo MVC solution, So I have implemented it like the below.

Declare the property like this.

[UIHint("DropDownTemplate")]
public IsAllowedCls IsAllowed { get; set; }

public class IsAllowedCls
{
    public int IsAllowedKey { get; set; }
    public string IsAllowedValue { get; set; }
}

Add view under Views\Shared\EditorTemplates create the view named as DropDownTemplate with below content

@model FxTrader.Models.IsAllowedCls

    @(Html.Kendo().DropDownList()
        .Name("DropDownTemplate")
        .DataValueField("IsAllowedKey")
        .DataTextField("IsAllowedValue")
        .BindTo((System.Collections.IEnumerable)ViewData["IsAllowedData"])
    )

In the controller action method, add the below code.

ViewData["IsAllowedData"] = new List<IsAllowedCls>() { new IsAllowedCls { IsAllowedKey = 1, IsAllowedValue = "Yes" },
    new IsAllowedCls { IsAllowedKey = 0, IsAllowedValue = "No" } };
0
David On

You can use the column template (documentation) to return a checkbox where the value is checked when the record's IsEnabled is Yes.

Then in the dataBound event of the grid (documentation) you would setup the event binding for the checkbox to get when the value changed.

Here is an example:

$('#grid').kendoGrid({
  columns: [
    {
        field: 'Name'
    },
    {
        field: 'name',
        template: function(dataItem) {
        var checkbox = $('<input />', {
          checked: dataItem.IsEnabled === 'Yes',
          type: 'checkbox'
        });
        return checkbox.prop('outerHTML');
      }
    }
  ],
  dataSource: [
    {
      Id: 1,
      Name: 'Person1',
      IsEnabled: 'Yes'
    },
    {
      Id: 2,
      Name: 'Person2',
      IsEnabled: 'No'
    },
    {
      Id: 3,
      Name: 'Person3',
      IsEnabled: 'No'
    }
  ],
  dataBound: function(e) {
    e.sender.table.on('change', 'input[type="checkbox"]', function() {
      var checked = this.checked;
      // send your AJAX request
    });
  }
});

Fiddle: https://dojo.telerik.com/igiTASAc