How to bind column to a field of complex object when object can be null

1 Answer 61 Views
Grid
kva
Top achievements
Rank 2
Iron
Iron
Iron
kva asked on 23 Aug 2023, 07:59 AM

I need grouping, filtering, sorting for a column. When I'm trying to bind to a field of an object which can be null, I get:

Uncaught TypeError: Cannot read properties of null (reading 'Name')

kva
Top achievements
Rank 2
Iron
Iron
Iron
commented on 24 Aug 2023, 06:22 AM | edited

I found that I can specify default model value simply:

public Department Department { get; set; } = new Department();

This way, I can bind to object's property. But when I modify editor to include:

HtmlAttributes(new { data_bind = "value: Department" })

I get:

VM53633:3 Uncaught TypeError: Cannot read properties of null (reading 'Name')
    at eval (eval at compile (kendo.all.js:307701:86), <anonymous>:3:239)
    at init._displayCell (kendo.all.js:307701:86)
    at init.closeCell (kendo.all.js:307701:86)
    at i (kendo.all.js:307701:86)
    at kendo.all.js:307701:86

Full editor's code:

@(Html.Kendo().ComboBoxFor(m => m)
    .DataTextField("Name")
    .DataValueField("Id")
    .Filter(FilterType.Contains)
    .HtmlAttributes(new { data_bind = "value: Department" })
    .DataSource(source =>
    {
        source.Read(read =>
        {
            read.Action("GetDepartments", "Home");
        });
    }))

Department:

    public class Department : Entity
    {
        public string Name { get; set; } = string.Empty;
        
        public virtual List<User> Users { get; set; }
        public virtual List<Project> Projects { get; set; }
    }

Without call to HtmlAttributes in editor, anything runs without exceptions, but instead of showing Name's value, grid shows [Object object].

I'm using telerik 2022.1.301 with .net core 3.1.

kva
Top achievements
Rank 2
Iron
Iron
Iron
commented on 25 Aug 2023, 06:44 AM

I found that this was the problem with ComboBox editor. Actually, DropDownList suits my needs, so I switched to it, and it works without errors.

1 Answer, 1 is accepted

Sort by
0
Accepted
kva
Top achievements
Rank 2
Iron
Iron
Iron
answered on 28 Aug 2023, 05:32 AM | edited on 28 Aug 2023, 05:34 AM

I found that we can just specify:

        columns.Bound(p => p.Department.Name).Width(230)
            .ClientTemplate("#=data.Department?.Name ?? ''#")
This means what we can bind to filtering property and show it from object. There will be no exceptions thrown.
Tags
Grid
Asked by
kva
Top achievements
Rank 2
Iron
Iron
Iron
Answers by
kva
Top achievements
Rank 2
Iron
Iron
Iron
Share this question
or