Click here to Skip to main content
15,887,596 members
Articles / Web Development / HTML
Tip/Trick

Using Kendo UI Grid with ASP.NET MVC5 Web API

Rate me:
Please Sign up or sign in to vote.
4.79/5 (10 votes)
29 Apr 2015CPOL 46.1K   2.2K   11   6
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)


Written By
Software Developer (Senior) Success Software Services
Vietnam Vietnam
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionCopy paste from telerik web site - nothing new. Pin
Vitaliy Markitanov15-Sep-17 5:28
Vitaliy Markitanov15-Sep-17 5:28 
PraiseGood Job! Pin
sharpe785229-Oct-16 7:03
sharpe785229-Oct-16 7:03 
QuestionSource code file is corrupted ? Pin
touseef4pk13-Apr-16 7:01
touseef4pk13-Apr-16 7:01 
QuestionQuestions Pin
Alireza_136219-Feb-16 3:50
Alireza_136219-Feb-16 3:50 
QuestionDefaultApi to ActionApi not found error Pin
Member 157617719-Aug-15 11:51
Member 157617719-Aug-15 11:51 
GeneralMy vote of 4 Pin
Santhakumar Munuswamy @ Chennai1-May-15 21:18
professionalSanthakumar Munuswamy @ Chennai1-May-15 21:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.