65.9K
CodeProject is changing. Read more.
Home

Using Kendo UI Grid with ASP.NET MVC5 Web API

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.79/5 (9 votes)

Apr 29, 2015

CPOL
viewsIcon

47533

downloadIcon

2169

How to use Kendo UI Grid with Web API

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

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.

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:

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:

@(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.
function sync_handler(e)
{
    this.read();
}

History

  • 2015.04.29 - Initial version