Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Using Kendo UI Grid with ASP.NET MVC5 Web API

4.79/5 (10 votes)
29 Apr 2015CPOL 47.5K   2.2K  
How to use Kendo UI Grid with Web API

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

Introduction

This is a quick guide for using ASP.NET MVC5 WebAPI, Entity Framework as a remote data source for Kendo UI, as well as performing some operations like Edit and Delete records.

Using the Code

We need to create a new Web API Project + Kendo UI. And then follow some steps below:

Step 1 - Create View Model

C#
public class OrderViewModel
{
    public int OrderID { get; set; }                
    public DateTime? OrderDate { get; set; }
    public string CustomerID { get; set; }
    public string ShipName { get; set; }
    public string ShipAddress { get; set; }  
    public string ShipCity { get; set; }
}

Step 2 - Create API Controller

After creating a ASP.NET MVC5 WebAPI Project, we need to add API Controller that has name ApiHomeController with some actions: Read, Edit and Delete.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Kendo.Mvc.UI;

public class ApiHomeController : ApiController
{
    /// <summary>
    /// Read event of Kendo UI Grid
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    [HttpGet]
    public DataSourceResult ReadOrders( [ModelBinder
        (typeof(WebApiDataSourceRequestModelBinder))] DataSourceRequest request)
    {
        var gridData = GetOrders();
        var result = new DataSourceResult()
        {
            Data = gridData,
            Total = gridData.Count
        };

        return result;
    }

    /// <summary>
    /// Delete event of Kendo UI Grid
    /// </summary>
    /// <param name="request"></param>
    /// <param name="order"></param>
    /// <returns></returns>
    [HttpDelete]
    public HttpResponseMessage DeleteOrders( [ModelBinder
     (typeof(WebApiDataSourceRequestModelBinder))] DataSourceRequest request, OrderViewModel order)
    {
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        if (order != null)
        {
            var northwind = new NorthwindEntities();
            List<Order_Detail> orderDetailsDelete = northwind.Order_Details.Where
               (m => m.OrderID == order.OrderID).ToList();
            Order orderDelete = northwind.Orders.First(m => m.OrderID == order.OrderID);
            foreach (var item in orderDetailsDelete)
            {
                northwind.Order_Details.Remove(item);
            }

            northwind.SaveChanges();

            northwind.Orders.Remove(orderDelete);
            northwind.SaveChanges();
        }

        return response;
    }

    /// <summary>
    /// Edit event of Kendo UI Grid
    /// </summary>
    /// <param name="request"></param>
    /// <param name="order"></param>
    /// <returns></returns>
    [HttpPut]
    public HttpResponseMessage EditOrders( [ModelBinder(typeof
       (WebApiDataSourceRequestModelBinder))] DataSourceRequest request, OrderViewModel order)
    {
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        if (order != null && ModelState.IsValid)
        {
            var northwind = new NorthwindEntities();
            Order orderUpdate = northwind.Orders.First(m => m.OrderID == order.OrderID);
            orderUpdate.OrderDate = order.OrderDate;
            orderUpdate.ShipName = order.ShipName;
            orderUpdate.ShipAddress = order.ShipAddress;
            orderUpdate.ShipCity = order.ShipCity;
            northwind.SaveChanges();
        }
        else
        {
            response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Validation Failed");
        }

        return response;
    }

    /// <summary>
    /// Get data from Northwind Database
    /// </summary>
    /// <returns></returns>
    private List<OrderViewModel> GetOrders()
    {
        var northwind = new NorthwindEntities();
        return northwind.Orders.Select(order => new OrderViewModel
        {
            OrderID = order.OrderID,
            CustomerID = order.CustomerID,
            OrderDate = order.OrderDate,
            ShipName = order.ShipName,
            ShipAddress = order.ShipAddress,
            ShipCity = order.ShipCity
        }).ToList();
    }
}

Step 3 - Config WebApi Route

Add new route ActionApi on App_Start\WebApiConfig.cs as follows:

C#
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "ActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Step 4 - Create a View with Kendo Grid Control

Read, Edit and Destroy events will call from WebApi, as follows:

C#
@(Html.Kendo().Grid<OrderViewModel>()
    .Name("gridKendo")
    .Columns(columns =>
    {
        columns.Bound(o => o.OrderID);
        columns.Bound(o => o.CustomerID);
        columns.Bound(o => o.OrderDate).Format("{0:MM/dd/yyyy}").Width
                      (190).EditorTemplateName("DateTime");
        columns.Bound(o => o.ShipName);
        columns.Bound(o => o.ShipAddress).Width(110);
        columns.Bound(o => o.ShipCity).Width(110);
        columns.Command(command => { command.Edit(); command.Destroy(); }).Width(220);
    })
    .Editable(editable => editable.Mode(GridEditMode.InLine))        
    .Pageable(pageable => pageable
        .Refresh(true)
        .PageSizes(true)
        .ButtonCount(5))
    .DataSource(dataSource => dataSource
        .WebApi()
        .PageSize(20)
        .ServerOperation(false)             
        .Model(model =>
            {
                model.Id(o => o.OrderID);
                model.Field(o => o.OrderID).Editable(false);
                model.Field(o => o.CustomerID).Editable(false);
            })
        .Read(read => read.Url(Url.HttpRouteUrl("ActionApi", 
                                  new { controller = "ApiHome", action = "ReadOrders" })))
        .Update(update => update.Url(Url.HttpRouteUrl("ActionApi", 
                                  new { controller = "ApiHome", action = "EditOrders" })))
        .Destroy(update => update.Url(Url.HttpRouteUrl("ActionApi", 
                                  new { controller = "ApiHome", action = "DeleteOrders" })))
        .Events(events => events.Sync("sync_handler"))
    )
)
JavaScript function sync_handler will call read events of Kendo Grid to refresh data after Edit or Delete.
JavaScript
function sync_handler(e)
{
    this.read();
}

History

  • 2015.04.29 - Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)