Search code examples
c#.net-corerazorblazorsyncfusion

How To Use Blazor Syncfusion SfGrid with nested object


I am using a Syncfusion Grid to display a list of ChildRecord objects. The ChildRecord class contains a Name class. The Name class contains the child's first name and last name as strings. For some reason, the grid is displaying the variables inside the Name object as blank. I have attached the relevant code.

<SfGrid DataSource="@ChildRecords" AllowPaging="true" AllowSorting="true" AllowFiltering="true" AllowGrouping="true">
<GridPageSettings PageSize="5"></GridPageSettings>
<GridColumns>
    <GridColumn Field=@nameof(ChildRecord.Name.FirstName) HeaderText="First Name" Width="150"></GridColumn>
    <GridColumn Field=@nameof(ChildRecord.Name.LastName) HeaderText="Last Name" Width="150"></GridColumn>
    <GridColumn Field=@nameof(ChildRecord.ID) HeaderText="ID" Width="150"></GridColumn>
    <GridColumn Field=@nameof(ChildRecord.DoB) HeaderText="DoB" Width="150"></GridColumn>
</GridColumns>

Here is how the table renders in the Blazor app: enter image description here

I hypothesize that SfGrid is internally implemented in a way that does not support nested objects. I would like to know if there is a workaround for this issue.


Solution

  • You want to display a nested property (complex data) value in the Grid. You can achieve complex data binding in the DataGrid by using the dot (.) operator in the column.field. In the following examples, Name.FirstName and Name.LastName are complex data.

    Reference:

    https://blazor.syncfusion.com/documentation/datagrid/columns#complex-data-binding

    <SfGrid DataSource="@Employees" Height="315"> 
        <GridColumns> 
            <GridColumn Field=@nameof(EmployeeData.EmployeeID) HeaderText="EmployeeID" TextAlign="TextAlign.Right" Width="120"></GridColumn> 
            <GridColumn Field="Name.FirstName" HeaderText="First Name" Width="150"></GridColumn> 
            <GridColumn Field="Name.LastName" HeaderText="Last Name" Width="130"></GridColumn> 
            <GridColumn Field=@nameof(EmployeeData.Title) HeaderText="Title" Format="C2" TextAlign="TextAlign.Right" Width="120"></GridColumn> 
        </GridColumns> 
    </SfGrid> 
    
    @code{ 
      ... 
    
      public class EmployeeData 
      { 
        public int? EmployeeID { get; set; } 
        public EmployeeName Name { get; set; } 
        public string Title { get; set; } 
      }  
    
      public class EmployeeName 
      { 
        public string FirstName { get; set; } 
        public string LastName { get; set; } 
      } 
    }