How to bind Kendo UI Grid to Web API Controller?

15,269

Solution 1

Have a look at the examples, it expects a DataSourceResult. In your controller include a method that does something like this, then it works.

I am looking at creating an aspect with postsharp that would introduce the create/update/delete methods in the controller class that Kendo requires.

using Kendo.Mvc.Extensions;

  public DataSourceResult Read([DataSourceRequest] DataSourceRequest request)
        {
            return this.Get().ToDataSourceResult(request);
        }

I think it is actually weird that Kendo does not provide an attribute/aspect for this for the API controller classes, but maybe I am missing something..

Solution 2

I also had troubles getting Kendo to work for an API controller. For me, it worked to switch from using Kendo.Mvc.Extensions to using Kendo.DynamicLinq.

In my Kendo datasource, I removed the mysterious line type: aspnetmvc-ajax and the parameterMap.

Share:
15,269
Dave
Author by

Dave

Updated on June 22, 2022

Comments

  • Dave
    Dave almost 2 years

    I'm having trouble binding data from a Web API Controller to a Kendo UI grid. Unfortunately I haven't been able to find any examples of this.

    Here's the API Controller:

    public class FruitController : ApiController
    {
        public class Fruit
        {
            public string Name { get; set; }
            public string Color { get; set; }
        }
    
        public IEnumerable<Fruit> GetFruits()
        {
            List<Fruit> list = new List<Fruit>();
    
            Fruit f = new Fruit();
            f.Name = "Apple";
            f.Color = "Red";
    
            list.Add(f);
    
            f = new Fruit();
            f.Name = "Kiwi";
            f.Color = "Green";
    
            list.Add(f);
    
            return list;
        }
    }
    

    And in my .cshtml file I have:

     @model IEnumerable<FruitController.Fruit>
    
        @(Html.Kendo().Grid(Model)    
            .Name("Grid")
            .Columns(columns =>
            {
                columns.Bound(p => p.Name);
                columns.Bound(p => p.Color);
            })
            .Groupable()
            .Pageable()
            .Sortable()
            .Scrollable()
            .Filterable()
            .DataSource(dataSource => dataSource
                .Ajax()
                .Read(read => read.Action("GetFruits", "api/Fruit").Type(HttpVerbs.Get)
    
                )
            )
        )
    

    When I run this, I get a successful JSON response from the controller:

    [{"Name":"Apple","Color":"Red"},{"Name":"Kiwi","Color":"Green"}]

    But the grid has no data in it. Is there something obvious I am missing? I haven't been able to figure this out!

    Thanks!