Kendo grid - adding column from nested dictionary

2019-08-03 16:11发布

    [Serializable]
    public class ContactDto
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string CompanyName { get; set; }
        public Dictionary<string, string> CustomFields { get; set; }
    }

I have the contactdto class above with a dictionary of customfields. Those can be anything 'MotherName' 'Birthdate' etc.

How do i display the custom fields as columns in the kendo grid? All the contactDTO's will have the same dictionary keys. I am using the ASP.net MVC helpers.

I have tried something like - which does not work -

@(Html.Kendo().Grid<ContactDto>(Model)
.Name("ReportViewer-Data")
.Columns(columns =>
{
    columns.Bound("FirstName");
    columns.Bound("LastName");
    columns.Bound("CustomFields.Industry");
})
.Sortable()
.Pageable(pageable => pageable.PageSizes(true).ButtonCount(5))
.Groupable()
.Selectable(selectable => selectable.Mode(GridSelectionMode.Multiple))
.Resizable(resize => resize.Columns(true))
.Reorderable(reorder => reorder.Columns(true))
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("DataView_Test", "Reports"))
)
)

1条回答
啃猪蹄的小仙女
2楼-- · 2019-08-03 17:05

Assuming your json data from backend would similar to this

data: [{
    FirstName: "John",
    LastName: "Doe",
    CustomField: {
        BirthDate: "9 June 1999",
        MotherName: "Valen"
    }
}, {
    FirstName: "Ray",
    LastName: "Doe",
    CustomField: {
        BirthDate: "9 June 1998",
        MotherName: "Valen"
    }
}, {
    FirstName: "Grey",
    LastName: "Doe",
    CustomField: {
        BirthDate: "9 June 1997",
        MotherName: "Valen"
    }
}]

Since kendo dataSource currently does not support complex data type like array and object.

The workaround would be to add schema to your dataSource like this

schema: {
    parse: function (response) {
        var items = [];
        for (var i = 0; i < response.length; i++) {
          console.log(response);
            var item = {
                FirstName: response[i].FirstName,
                LastName: response[i].LastName,
                BirthDate: response[i].CustomField.BirthDate,
                Mother: response[i].CustomField.MotherName
            };

            items.push(item);
        }
        return items;
    },
    pageSize: 20
},

After you get data and the dataSource will parse customField which is nested to normal field. Please refer to this working example.

查看更多
登录 后发表回答