Search code examples
asp.net-corerazordevextreme

How do I handle a null data condition in DevExtreme DataGrid template?


I have the following class definition:

public class SubType
{
    [Key] 
    public Guid SubTypeId { get; set; }
    public string SubTypeName { get; set; }
}
public class Item
{
    [Key] 
    public Guid ItemId { get; set; }
    public string Name { get; set; }
    public string Variety { get; set; }
    public SubType ItemSubType { get; set;}
}

Here is my DevExtreme DataGrid definition:

@(Html.DevExtreme().DataGrid<Item>()
    .DataSource(Model)
    .Columns(columns => {
        columns.AddFor(m => m.Name);
        columns.AddFor(m => m.Variety);
    })
    .MasterDetail(md => {
        md.Enabled(true);
        md.Template(@<text>
            <div class="master-detail-caption">SubType: <%- data.ItemSubType.SubTypeName%> </div>
        </text>);
    })

When data.ItemSubType is NULL, I get the following error:

VM28:3 Uncaught TypeError: Cannot read property 'SubTypeName' of null at eval (eval at (dx.aspnet.mvc.js:75), :3:145) at Object.render (dx.aspnet.mvc.js:85) at t.n._renderCore (dx.all.js:80) at t.render (dx.all.js:15) at t._renderDelayedTemplatesCore (dx.all.js:42) at t.renderDelayedTemplates (dx.all.js:42) at t.renderDelayedTemplates (dx.all.js:107) at t.renderDelayedTemplates (dx.all.js:10) at t.renderDelayedTemplates (dx.all.js:112) at t.renderDelayedTemplates (dx.all.js:10)

When Data.ItemSubType is not null, SubTypeName displays without error.

How do I handle the case where ItemSubType is null? Is there way to conditionally display a default string/value when it's null?


Solution

  • Use a conditional operator a ? b : c

    <%- data.ItemSubType != null? data.ItemSubType.SubTypeName : "NoSubType"%>