How to add KendoUI Grid Control and perform CRUD with ASP MVC.

This is a step by step guide to add KendoUI Grid to ASP MVC project. Below are the steps to create a grid for our Company lists.

1. Create a HomeController

Add CRUD operation action method to Home controller, these action methods will be call by KendoUI grid datasource later.

using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using SamuraiListing.Data;

namespace SamuraiListing.Controllers
{
    public class HomeController : Controller
    {
        // Declare database UoW - SamuraiListing.Data.Database
        private readonly Database _database = new Database();

        public ActionResult Index()
        {
            return View();
        }

        // Action method to get all the companies.
        // DataSourceRequest is aded into the method for the auto creation of KendoUI grid parameters like page, index etc.
        public ActionResult GetAll([DataSourceRequest] DataSourceRequest request)
        {
            // Retrieve all the companies from database.
            var companies = _database.Companies.GetAll();
            // Return the companies in json format back to KendoUI grid.
            // Anonymous type selector is added to prevent circular reference of json with entity framework.
            return Json(companies.ToDataSourceResult(request, record => new
            {
                record.Id,
                record.Name,
                record.Telephone,
                record.Email,
                record.GPS
            }));
        }

        // Action method to add new company to databaes.
        // Accecpt only HTTP POST request.
        // DataSourceRequest is aded into the method for the auto creation of KendoUI grid parameters like page, index etc.
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add([DataSourceRequest] DataSourceRequest request, Company company)
        {
            // Test if company object and modelstate is valid.
            if (company != null && ModelState.IsValid)
            {
                // Add company to UoW.
                _database.Companies.Add(company);
                // Save company to database using UoW.
                _database.Save();
            }
            // Return added company record back to client side in json format and embeded request, modelstate information.
            return Json(new[] {company}.ToDataSourceResult(request, ModelState));
        }

        // Action method to update company record to database.
        // Accecpt only HTTP POST request from client side.
        // DataSourceRequest is aded into the method for the auto creation of KendoUI grid parameters like page, index etc.
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Update([DataSourceRequest] DataSourceRequest request, Company company)
        {
            // Test if company object and modelstate is valid.
            if (company !=null && ModelState.IsValid)
            {
                // Update company to UoW.
                _database.Companies.Update(company);
                // Save updated company to database using UoW.
                _database.Save();
            }
            // Return modelstate info back to client side in json format.
            return Json(ModelState.ToDataSourceResult());
        }

        // Action method to delete company record from database.
        // Accecpt only HTTP POST request from client side.
        // DataSourceRequest is aded into the method for the auto creation of KendoUI grid parameters like page, index etc.
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete([DataSourceRequest] DataSourceRequest request, Company company)
        {
            // Test if company object and modelstate is valid.
            if (company != null && ModelState.IsValid)
            {
                // Delete company from UoW.
                _database.Companies.Delete(company);
                // Call to database and delete the deleted record.
                _database.Save();
            }
            // Return modelstate info back to client side in json format.
            return Json(ModelState.ToDataSourceResult());
        }
    }
}

2. Add KendoUI Grid to Index.cshtml.

I’m using KendoUI ASP wrapper and razor in the code below to add kendoui grid.

@{
    ViewBag.Title = "Index";
}</pre>
<h2>Samurai Listing - KendoUI ASP MVC4 Project</h2>
<h2>Company Grid Example</h2>
<pre>
// KendoUI Grid that use Company Model.
@(Html.Kendo().Grid<SamuraiListing.Data.Company>()
    // Grid Name
    .Name("CompanyGrid")

    // Declare grid column
    .Columns(columns =>
                 {
                     // Cretae all the columns base on Model
                     columns.Bound(r => r.Name);
                     columns.Bound(r => r.Telephone);
                     columns.Bound(r => r.Email);
                     columns.Bound(r => r.GPS);

                     // Edit and Delete button column
                     columns.Command(command =>
                                         {
                                             command.Edit();
                                             command.Destroy();
                                         }).Width(200);
                 })

    // Declare ajax datasource.
    // CRUD operation are wired back to ASP MVC Controller/Action e.g. HomeController, GetAll
    // Set the model Id
    .DataSource(datasoure => datasoure.Ajax()
                                .Model(model => model.Id(record => record.Id))
                                .Read(read => read.Action("GetAll", "Home"))
                                .Create(create => create.Action("Add", "Home"))
                                .Update(update => update.Action("Update", "Home"))
                                .Destroy(delete => delete.Action("Delete", "Home"))
                                .PageSize(10)
    )

    // Add tool bar with Create button
    .ToolBar(toolbar => toolbar.Create())

    // Set grid editable.
    .Editable(editable => editable.Mode(GridEditMode.InLine))

    // Set grid sortable.
    .Sortable()

    // Set grid selectable.
    .Selectable()

    // Set grid pagable.
    .Pageable(pageable =>
                  {
                      pageable.Refresh(true);
                      pageable.PageSizes(true);
                  })
)

3. Hit “F5”

You should be able to see the result similar to below, with that, you can use the grid to add companies to our SamuraiListing database. I have added Bizvise companies and our subsidiaries to the list. 😉

 Add KendoUI Grid to ASP MV Project | SamuraiListing

You can download the complete source code (SamuraiListing Part 2) from this link.

With that I ended my blog post of this tutorial series, further development of SamuraiListing can be found on codeplex. You are most welcome to improve this example. Thanks and Happy Coding!

Important Note:

You are looking at one of the blog post I completed in a tutorial series about KendoUI and ASP MVC4, you can find out the Table of Content on - Simple KendoUI Example – SamuraiListing


Step 1 – How to create KendoUI ASP MVC 4 project.
Step 2 - How to Create a SQL Database Project for ASP MVC in Visual Studio 2012
Step 3 - How to create a simple data access layer using Repository Pattern with Entity Framework
Step 4 - How to create a simple data access layer Unit of Work pattern with Entity Framework
Step 5 - How to add Database and DataModel class to ASP MVC4 project.
Step 6 - How to add KendoUI Grid Control and perform CRUD with ASP MVC.

Advertisements

11 comments

  1. Pingback: Simple KendoUI Example – SamuraiListing | BizVise - Melaka Software Development

  2. I figured out
    To razor i added line:
    columns.ForeignKey(p => p.ServiceId, (System.Collections.IEnumerable)ViewData[“services”], “Id”, “Name”);
    and controller:
    private readonly KendoPartcomDb _kendoPartcomDb = new KendoPartcomDb();
    private void PopulateServices()
    {

    List ServiceList = new List();
    ServiceList = _kendoPartcomDb.Service.ToList();
    ViewData[“services”] = ServiceList;

    }
    and it works.

    Like

  3. Hi mister. i’m a beginer using EF models.. so, i follow u example, but i can’t see _database.Companies.GetAll(); method.
    this is a standart method generated by EF?, or i need make my own code for this one method?.
    Thanks in advance.

    Like


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s