Grid - Binding doesn't work

2 Answers 3789 Views
Grid
Cool Apps
Top achievements
Rank 2
Cool Apps asked on 16 Mar 2017, 12:34 PM
Read doesn't work :(


Here's the view:
@*@(Html.Kendo().Grid(Model.Forms)*@ - this one works, unlike the other two which are used with
    @*@(Html.Kendo().Grid<CTR.Models.Forms.Form>()*@
    @(Html.Kendo().Grid<CTR.Models.FormsViewModels.FormViewModel>()
            .Name("Forms")
            .Columns(columns =>
            {
                columns.Bound(p => p.ID);
                columns.Bound(p => p.Type);                
            })                                    
            .DataSource(datasource => datasource
                .Ajax()                                
                .Read(read => read.Action("List1", "Forms"))                
            )
    )

this works
public ActionResult Index()
        {
            var forms = _context.Forms.ToList();
            var model = new ListViewModel(forms);
            return View(model);
        }

None of the Read actions work, i.e. the grid receives zero items.
The actions do return data:
{"data":[{"id":3,"type":0,"questions":null},{"id":2,"type":0,"questions":null},{"id":1,"type":0,"questions":null}],"total":3,"aggregateResults":null,"errors":null}

        public async Task<IActionResult> List([DataSourceRequest] DataSourceRequest request)
        {
            var forms = await _context.Forms.ToListAsync<Form>();
            var list = new List<FormViewModel>();
            forms.ForEach(x => list.Add(new FormViewModel(x)));

            DataSourceResult result = await list.ToDataSourceResultAsync(request);
            return Json(result);
        }

        public ActionResult List1([DataSourceRequest] DataSourceRequest request)
        {            
            var forms = _context.Forms.ToList<Form>();
            var list = new List<FormViewModel>();
            forms.ForEach(x => list.Add(new FormViewModel(x)));
            
            DataSourceResult result = list.ToDataSourceResult(request);
            return Json(result);
        }

        public async Task<ActionResult> List2([DataSourceRequest] DataSourceRequest request)
        {
            IQueryable<Form> forms = _context.Forms;
            DataSourceResult result = await forms.ToDataSourceResultAsync(request);
            return Json(result);
        }




Cool Apps
Top achievements
Rank 2
commented on 16 Mar 2017, 12:35 PM

Just FYI - I've read http://docs.telerik.com/aspnet-mvc/helpers/grid/binding/ajax-binding

2 Answers, 1 is accepted

Sort by
2
Accepted
Viktor Tachev
Telerik team
answered on 23 Mar 2017, 01:59 PM
Hi Brandon,

I have examined the code and noticed that the field names returned from the server in the JSON are using camelCase. However, the fields in the model are specified with PascalCase. Because of this the data is not displayed correctly. 

Please ensure that you modify the ConfigureServices method in Startup.cs as described in step 4 in the article below:


The method should look similar to this:

public void ConfigureServices(IServiceCollection services)
    {
        ...
        // Maintain property names during serialization. See:
        services
            .AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
 
        // Add Kendo UI services to the services container
        services.AddKendo();
    }


Give the modification a try and let me know how it works for you.


Regards,
Viktor Tachev
Telerik by Progress
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Brandon
Top achievements
Rank 1
commented on 23 Mar 2017, 02:49 PM

Viktor,

You're the man! Ajax not working in grid binding has been the reason for me not fully committing to this product! I've read everything I could about the ASP.NET CORE configuration and demos around the Kendo controls but this one slipped through the cracks.

I've implemented the startup.cs Json options change and the grids now work perfectly with the Ajax calls!

Thanks,
Brandon

Doug
Top achievements
Rank 2
commented on 14 Apr 2019, 12:59 AM

Thanks, this fixed my binding issue as well.
neil fennessey
Top achievements
Rank 1
commented on 19 Aug 2019, 03:56 PM

Hi, Thank you. It solved my problem also. 

But I have question here what if we used model class in property names are define in same as Json return results.

For example , I tried below class,

public class UserTemp
    {
        public string firstName { get; set; }
        public string lastName { get; set; }
    }

 

And Kendo grid as below ,

 

@(Html.Kendo().Grid<Aquatrols.Entity.UserTemp>()
    .Name("grid")
    .DataSource(dataSource => dataSource
    .Ajax()
    .Read(read => read.Action("Customers_Read", "KendoGrid"))
    )
    .Columns(columns=>
    {
        columns.Bound(userdata => userdata.firstName);
      
    })
    .Pageable()
    .Sortable()
    )

With this approach , data returns when I checked in browser using developer tools but not binding the grid.

 

My problem is that here if make changes in startup.cs file for Json option mentioned as above then data will return in PascalCase that will work for this grid but at many ares where I used DataTable and for that I already mentioned column name in camelCase.

 

Please help out here.

Viktor Tachev
Telerik team
commented on 22 Aug 2019, 10:19 AM

Hi Neil,

 

By default the DataSource component expects the data to be serialized in specific format. The items returned from the server to the DataSource are available in a field named Data. When JSON serialization is not specified that field will be serialized as data and the widget will not be able to read the items. 

In order to work around this you can define Custom DataSource for the Grid and explicitly set the schema.data and schema.total fields. For convenience I have prepared a sample project where the approach is illustrated. Give it a try and let me know how it works for you.

 

Regards, Viktor Tachev
Progress Telerik

Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
REAG
Top achievements
Rank 1
commented on 11 Nov 2019, 11:22 AM

Don't forget to include "using Newtonsoft.Json.Serialization;" and download the Newtonsoft.Json nuget package, otherwise that yellow-highlighted line of code won't work.
Carl
Top achievements
Rank 1
commented on 11 Nov 2019, 05:23 PM

Please consider my suggestions for improvements at

https://www.telerik.com/forums/data-binding-and-serialization-issue-with-system-text-json-core-3-0#HexPBMLG5kuVoDXc1hHcRQ

Thanks...

Viktor Tachev
Telerik team
commented on 14 Nov 2019, 09:26 AM

Hi Carl,

 

As Veselin has noted in the thread we will include the suggestion in our backlog and will introduce additional documentation resources as soon as possible. Thank you for the suggestion.

 

Regards,
Viktor Tachev
Progress Telerik

Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
Viktor Tachev
Telerik team
answered on 20 Mar 2017, 02:28 PM
Hello Ivaylo,


The behavior you describe can be observed if the kendo.aspnetmvc.min.js is not referenced in the project. Please ensure that it is added to the application and that it is after kendo.all.min.js and see how the behavior changes.




Regards,
Viktor Tachev
Telerik by Progress
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Cool Apps
Top achievements
Rank 2
commented on 22 Mar 2017, 10:06 AM

Hey Victor,

I've checked and this is not the problem.
<script src="@Url.Content("~/Scripts/kendo/kendo.all.min.js")"></script>  
<script src="@Url.Content("~/Scripts/kendo/kendo.aspnetmvc.min.js")"></script>

Both scripts are loaded properly (checked chrome dev console).
I am using v.2017.1.223  - SP1

Also, the grid performs POST, so this should be fine too.
Request URL:
http://localhost:50275/Forms/List
Request Method:
POST
Status Code:
200 OK

Response:
{"data":[{"id":1029,"type":0,"questions":null},{"id":3,"type":0,"questions":null},{"id":2,"type":0,"questions":null},{"id":1,"type":0,"questions":null}],"total":4,"aggregateResults":null,"errors":null}

Brandon
Top achievements
Rank 1
commented on 22 Mar 2017, 09:07 PM

I also have no luck with this issue. I can see using the developer tools in Chrome that my Json data is returned in full with 200 status code but the grid never rebinds to show the data. The only way I can get my grids to bind is to bind to the View model on the initial View page load which makes partial view and other loading types worthless.

This must be a bug. Referencing a grid as the following doesnt work:

@(Html.Kendo().Grid<Codes>()
                    .Name("CodesGrid")
                    .Columns(columns =>
                    {
                        //columns.Command(command => { command.Edit(); }).Width(60);
                        columns.Bound(o => o.CodeId);
                        columns.Bound(o => o.FieldName);
                        columns.Bound(o => o.FieldDescription);
                        columns.Bound(o => o.FieldType);
                        columns.Bound(o => o.FieldValueType);
                        columns.Bound(o => o.IsRequired).ClientTemplate("<input type='checkbox' disabled='disabled' #= IsRequired ? checked='checked': checked='' # />");
                        columns.Bound(o => o.IsActive).ClientTemplate("<input type='checkbox' disabled='disabled' #= IsActive ? checked='checked': checked='' # />");
                        columns.Bound(o => o.CreatedBy);
                        columns.Bound(o => o.CreatedOn).Width(180).Format("{0:MM/dd/yyyy hh:mm tt}");
                    })
                //.ToolBar(toolbar => toolbar.Create())
                .Pageable()
                .Sortable()
                .Filterable()
                //.Editable(editable => editable.Mode(GridEditMode.InLine))
                .DataSource(dataSource => dataSource
                .Ajax()
                .ServerOperation(false)
                .PageSize(50)
                .Events(events => events.Error("error_handler"))
                .Model(model =>
                {
                    model.Id(o => o.CodeId);
                    model.Field(o => o.IsActive).DefaultValue(true);
                    model.Field(o => o.IsRequired).DefaultValue(false);
                    model.Field(o => o.CreatedBy).Editable(false);
                    model.Field(o => o.CreatedOn).Editable(false);
                })
                .Read(r => r.Action("GetCodes", "SysAdmin")))
     )

 

Binding returns Json data using method :

public ActionResult GetCodes([DataSourceRequest] DataSourceRequest request)
        {
            return Json(_sysAdminService.GetCodes().ToDataSourceResult(request));
        }

 

But this works:

@(Html.Kendo().Grid(Model) ...

 

public IActionResult Codes()
        {
            var model = _sysAdminService.GetCodes();;
            return View(model);
        }

 

Gabriel
Top achievements
Rank 2
commented on 31 Jan 2020, 03:48 PM

Hello Admin, I have a similar problem and tried to access your answer, but it's a 404. I would like to find help on this matter. Can you provide another link? 
Thank you!
Tsvetomir
Telerik team
commented on 05 Feb 2020, 10:35 AM

Hi Gabriel,

The getting started section for the ASP.NET Core widgets has been remodeled. You could find the serialization-related article here:

https://docs.telerik.com/aspnet-core/getting-started/prerequisites/environment-support

 

Regards,
Tsvetomir
Progress Telerik

Get quickly onboarded and successful with Telerik UI for ASP.NET Core with the dedicated Virtual Classroom technical training, available to all active customers.
Kim
Top achievements
Rank 1
Veteran
commented on 03 Jun 2020, 09:21 PM

Solved my issue too!  Thank you!
Ahmet
Top achievements
Rank 1
commented on 01 Aug 2022, 02:41 PM

I've been looking for this for 6 hours. I am happy to solve my problem. Extra: .net6 users can look at this page(https://docs.telerik.com/aspnet-core/installation/json-serialization) for "AddJsonOptions". 

builder.Services.AddControllersWithViews()
            // Maintain property names during serialization. See:
            // https://github.com/aspnet/Announcements/issues/194
            .AddJsonOptions(options =>
                options.JsonSerializerOptions.PropertyNamingPolicy = null)
Srinivasa
Top achievements
Rank 1
commented on 27 Jan 2023, 03:20 PM

Thank you, after adding this code to program.cs file every think started working
Tags
Grid
Asked by
Cool Apps
Top achievements
Rank 2
Answers by
Viktor Tachev
Telerik team
Share this question
or