New to Telerik UI for ASP.NET Core? Download free 30-day trial

Passing Default Date Value from Parent to Child Grid

Environment

Product Grid for Progress® Telerik® UI for ASP.NET Core
Product DataSource for Progress® Telerik® UI for ASP.NET Core

Description

I have a hierarchy Grid where I need to set the default value in the child's Grid to values from the parent, but I get an error. The value I need to set is a date. Here is my code:

    .Model(model => {
        model.Field(m => m.TestDate).DefaultValue("#= kendo.toString(TestDate,'dd/MM/yyyy') #");
    })

When I try to set the default value, I get the following error:

    Object of type 'System.String' cannot be converted to type 'System.Nullable'1[System.DateTime]'

I also tried with a non-nullable DateTime but got the same error except for the System.Nullable part.

Solution

The behavior you describe is expected because the Razor syntax expects a date type and such is not provided. The detail grids are evaluated on the client so the date cannot be passed via C# as it is not available at the time the child grid is created, it only becomes available once expanded.

I would suggest you use the Edit() event handler to find the master grid and master row and set the value to the new model programmatically instead:

    .Events(e=>e.Edit("addDefaultDate")).Events(e=>e.Edit("addDefaultDate"))

    function addDefaultDate(e) {
        if (e.model.isNew()) {
            var grid = this;
            var masterRow = grid.element.closest(".k-detail-row").prev();
            var masterGrid = $("#masterGridID").data("kendoGrid");
            var masterDataItem = masterGrid.dataItem(masterRow);
            e.model.set("TestDate" , masterDataItem.TestDate);
        }        
    }

More ASP.NET Core Grid Resources

See Also

In this article