Getting error when setting grid datasource: kendo.all.js:311085 Uncaught TypeError: Cannot read properties of undefined (reading 'id')

2 Answers 141 Views
Grid
Kevin
Top achievements
Rank 2
Iron
Iron
Iron
Kevin asked on 30 Sep 2022, 08:21 PM | edited on 30 Sep 2022, 08:29 PM

I have a grid I've created in MVC that is throwing the following error when I set the datasource

kendo.all.js:311085 Uncaught TypeError: Cannot read properties of undefined (reading 'id')

Using version 2022.2.802.545

Here is my grid

@(Html.Kendo().Grid<MyModelName>()
            .Name("event-violations-grid")
            .Columns(columns =>
            {
                //columns.Select().Width(50);
                columns.Bound(s => s.SupplierNumber).Hidden(true);
                columns.Bound(s => s.SupplierName).Width(275);
                columns.Bound(s => s.OldOrderDate).Format("{0:MM/dd/yyyy}").Hidden(true);
                columns.Bound(s => s.OldDeliveryDate).Format("{0:MM/dd/yyyy}").Hidden(true);
                columns.Bound(s => s.NewOrderDate).Format("{0:MM/dd/yyyy}").Hidden(true);
                columns.Bound(s => s.NewDeliveryDate).Format("{0:MM/dd/yyyy}").Hidden(true);
                columns.Bound(s => s.ArrivalDate).Format("{0:MM/dd/yyyy}").Hidden(true);
                columns.Bound(s => s.TransmitTime).Hidden(true);
                columns.Bound(s => s.ExpectedDeliveryTime).Hidden(true);
                columns.Bound(s => s.Action).Width(180);
                columns.Bound(s => s.ActionComments);
            })
            .Sortable()
            .Scrollable(s => s.Height("215px"))
            .HtmlAttributes(new { style = "height:250px;" })
            .Resizable(r => r.Columns(true))
        )

(I know there is a lot of hidden columns there.. I may or may not need them yet)

Then I have some javascript which populates a dataSource and sets to this grid

function getViolations() {
    var vdata = {};
    vdata["stageId"] = _stageId;
    vdata["stores"] = "" + _stores.join(',');
    vdata["supplierNumber"] = _eventRevertData.SupplierNumber;
    vdata["origDeliveryDate"] = kendoDateOnly(_eventRevertData.Start);
    vdata["newDeliveryDate"] = null;

    var dataSource = new kendo.data.DataSource({
        schema: {
            model: {
                fields: {
                    SupplierNumber: { type: "number" },
                    SupplierName: { type: "string" },
                    OldOrderDate: { type: "date" },
                    OldDeliveryDate: { type: "date" },
                    NewOrderDate: { type: "date" },
                    NewDeliveryDate: { type: "date" },
                    ArrivalDate: { type: "date" },
                    TransmitTime: { type: "string" },
                    ExpectedDeliveryTime: { type: "string" },
                    OrderGroup1: { type: "boolean" },
                    OrderGroup2: { type: "boolean" },
                    OrderGroup3: { type: "boolean" },
                    OrderGroup4: { type: "boolean" },
                    OrderGroup5: { type: "boolean" },
                    OrderGroup6: { type: "boolean" },
                    OrderGroup7: { type: "boolean" },
                    OrderGroup8: { type: "boolean" },
                    Action: { type: "string" },
                    ActionComments: { type: "string" }
                }
            }
        },
        transport: {
            read: {
                url: "/MyController/GetViolationsGrid1",
                data: vdata,
                dataType: "json"
            }
        }
    });
    dataSource.fetch(function () {
        let data = this.data();
        console.log(data);
        var grid = $("#event-violations-grid").data("kendoGrid");
        grid.setDataSource(data);
    });
}

This works - my grid displays exactly as I expect, and updates when I call my function (the vdata changes depending on other things)

However, I'm getting this error:

If I open that, I can see that the part of "my" code is here:

Which brings me to here

I have confirmed that I can get as far as line 1228 without issue.. my console.log works and I can see my data.. it seems like it is happening when I'm setting the data source

Any help would be greatly appreciated!

Thanks

 

2 Answers, 1 is accepted

Sort by
1
Eyup
Telerik team
answered on 05 Oct 2022, 07:46 PM

Hello Kevin,

 

Thank you for writing to us.

This probably happens because the current logic tries to set the data collection directly to the .setDataSource() method:

grid.setDataSource(data);

But this method expects the entire Kendo DataSource instance object:

grid.setDataSource(dataSource);

Therefore, can you try replacing the logic using the original dataSource object and try again?
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/setdatasource

Generally, you can also try the grid.refresh() method, which has proven to be very helpful in similar scenarios:
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/refresh

Let me know what you think.

 

Regards,
Eyup
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Kevin
Top achievements
Rank 2
Iron
Iron
Iron
commented on 11 Oct 2022, 01:24 PM

My issue is resolved.

To delve a little deeper here though.. Would refresh only pull in the current data items though?

I set that vdata object with some things - would it be interrogated again?  Or would it just refresh using what was in there already?
Eyup
Telerik team
commented on 14 Oct 2022, 10:13 AM

I am glad the issue is now resolved.

The answer depends on the chosen binding way of the grid. If the Grid is using client-side source or .Ajax() binding, it will reset only the data on the current page.

Here are some other methods to do that:

- grid.refresh()
- grid.dataSource.read()
- grid.dataSource.fetch()

0
Thomas
Top achievements
Rank 1
Iron
answered on 16 Nov 2022, 12:59 PM | edited on 16 Nov 2022, 01:12 PM

I am having the same identical issue when setting the dataSource for the grid after an update.  What was the specific resolution ?

I've tried the optional resolutions mentioned above but nothing changed.

Ajax success code below:

 

 
success: function (result) {
                        var grdClaimPayments = $("#ClaimsPayments").data("kendoGrid");
                        var data = result.Data;
                        var dataArray = [];
                        var total = result.Data.length;

                        if (data != null) {
                            for (var i = 0; i < data.length; i++) {
                                try {
                                    data[i].SubmissionDate = parseJsonDate(data[i].SubmissionDate);
                                    dataArray.push(data[i]);
                                    
                                }
                                catch (ex) {
                                    console.log("error" + ex);                                    
                                }
                            }
                           
                        }
                        var dataSource = new kendo.data.DataSource({
                            data: dataArray,
                            total: dataArray.total
                        });
                        grdClaimPayments.setDataSource(dataSource);
                        //grdClaimPayments.read();
                      
                    },                   

Anton Mironov
Telerik team
commented on 21 Nov 2022, 06:46 AM

Hi Thomas,

Thank you for the details provided.

As this is a copy of ticket #1587413 which I already answered, will copy my reply here as well. Please keep the communication in one thread in order to have the needed information available.

Thank you for the project provided.

I invested time and dive deeply into the implementation.

After a couple of tests, I can say that setting the dataSource for the "ClaimsPaymentDetails" Grid is not causing the pointed issue. In fact, the "GetClaimPaymentInfo" function is not calling as expected. The one dataItem that is populated is coming from the Post Method of the Form.

Furthermore, the Ajax Request in the GetClaimPaymentInfo function is searching for the "AccountingController" which does not exist.

In order to be more helpful, I decided to invest more time in creating the application from scratch. The custom implementations(debugging or developing) are in the scope of the Professional Services Team, but I really want to assist with achieving the desired result for this case, so here is what I could recommend:

  1. Use a Telerik UI Form(similar to the one from the example project that you sent me).
  2. Handle the "Submit" Event of the Form.
  3. In the event handler, the "preventDefault" behavior of the Form(it submitting).
  4. Get the field values of the Form(in the example below I will present the approach with one form field - "ShipName").
  5. Implement an Ajax Request to an Action Method in the Controller.
  6. Use the field values from point 4 as parameters for the Ajax Request and send them to the BackEnd.
  7. Receive the parameter/s in the Controller and use them in order to get the needed items for the Grid.
  8. Return the proper collection that should be used for the Grid.
  9. Receive the collection in the success scope of the Ajax Request and setDataSource to the Grid.
  10. Here is an example:
    // The Form:
    @(Html.Kendo().Form<TelerikMvcApp49.Models.OrderViewModel>()
            .Name("exampleForm")
            .HtmlAttributes(new { action = "Items", method = "POST" })
            .Validatable(v =>
            {
                v.ValidateOnBlur(true);
                v.ValidationSummary(vs => vs.Enable(true));
            })
            .Items(items =>
            {
                items.AddGroup()
                    .Label("Registration Form")
                    .Items(i =>
                    {
                        i.Add()
                            .Field(f => f.ShipName)
                            .Label(l => l.Text("ComboBox:"))
                            .Editor(e =>
                            {
                                e.ComboBox()
                                    .Placeholder("Select...")
                                    .Height(520)
                                    .DataSource(source =>
                                    {
                                        source.Read(read =>
                                        {
                                            read.Action("Items_GetShipNames", "Home");
                                        });
                                    });
                            });
                    });
            })
            .Events(ev => ev.Submit("onFormSubmit"))
        )
    
    // The Grid:
            @(Html.Kendo().Grid<TelerikMvcApp49.Models.OrderViewModel>()
                .Name("grid")
                .Columns(columns =>
                {
                    columns.Bound(p => p.OrderID).Filterable(false);
                    columns.Bound(p => p.Freight);
                    columns.Bound(p => p.ShipName);
                    columns.Bound(p => p.ShipCity);
                })
                .Pageable()
                .Sortable()
                .Scrollable()
                .Filterable()
                .HtmlAttributes(new { style = "height:250px;" })
                .DataSource(dataSource => dataSource
                    .Ajax()
                    .PageSize(20)
                )
            )
    
    // The Event handler:
        function onFormSubmit(e) {
            e.preventDefault();
    
            var shipName = e.model.ShipName;
    
            $.ajax({
                type: "POST",
                url: "Grid/GetGridData",
                data: JSON.stringify({
                    shipName: shipName
                }),
                cache: false,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (json) {
                    var grid = $("#grid").data("kendoGrid");
                    grid.setDataSource(json);
                }
            })
        }
    
    // The Action Methods:
    		private List<OrderViewModel> GetAllOrders()
    		{
    			var result = Enumerable.Range(1, 10).Select(i => new OrderViewModel
    			{
    				OrderID = i,
    				Freight = i * 10,
    				ShipName = "ShipName " + i,
    				ShipCity = "ShipCity " + i
    			});
    
    			return result.ToList();
    		}
    
    		public JsonResult GetGridData(string shipName)
    		{
    			List<OrderViewModel> allOrders = GetAllOrders();
    
    			List<OrderViewModel> resultOrders = allOrders.Where(o => o.ShipName == shipName).ToList();
    
    			return Json(resultOrders, JsonRequestBehavior.AllowGet);
    
            }

In ticket #1587413 is attached a sample project that I prepared for the case. It includes the approach above. 

Feel free to make the needed tests locally and let me know if this is the desired result.


Looking forward to hearing back from you.

Kind Regards,
Anton Mironov

Tags
Grid
Asked by
Kevin
Top achievements
Rank 2
Iron
Iron
Iron
Answers by
Eyup
Telerik team
Thomas
Top achievements
Rank 1
Iron
Share this question
or