Multiple Ways To Bind Data To Kendo Grid In MVC

Introduction

Many times, while working with Grid, we need to show the result into a GridView in different situations.

What is Kendo Grid?

The Kendo UI Grid is a powerful widget which allows you to visualize and edit data via its table representation. It provides many options, such as paging, sorting, filtering, grouping, and editing, which determine the way data is presented and manipulated.

The Grid can be bound to local or remote data by using the Kendo UI DataSource component.
 
Scenario I

Bind data to Kendo Grid by using AJAX Read action method.

Scenario II

Change the datasource on change event of any HTML controls.

Scenario I

Normally, a developer can bind the data to Grid by using AJAX Read method.

This read method is ActionResult method in MVC which will return JSON DataSourceResult & direclty bind the data to Grid. 

Note

Also, the developer can pass parameters to this read method. Suppose below is our read method.
  1. Read(read => read.Action("BindGrid""Home").Data("SortByCompanyId"))  
In the above line, my JavaScript function name is SortByCompanyId which will return company id. On that basis, we can pass parameter to our action method in Controller. 
  1. public ActionResult BindGrid([DataSourceRequest]DataSourceRequest request, string companyId)  
  2.        {  
  3.       // bind json data result here          
  4.     }  
Our JavaScript function is like the following.
  1. <script type="text/javascript">  
  2.         function SortByCompanyId() {  
  3.             var cId = 25;  
  4.             return {  
  5.                 companyId: cId  
  6.             }  
  7.         }  
  8.     </script>  
Step 1

Create a Model, give it a name as Company, and declare some properties into it.
  1. public class Company  
  2.     {  
  3.         public int Id { getset; }  
  4.         public string Name { getset; }  
  5.         public int? CompanyId { getset; }  
  6.     }  
Step 2

Now, create a Controller, give it name as HomeController. In this, create a action method as Index() which will return a View. On this View, write some code to bind data into the Grid View by using the above Model. 
  1. @model Grid.Models.Company  
  2. @using System.Web.Optimization  
  3. @using Kendo.Mvc.UI  
  4. @using Kendo.Mvc.Extensions  
  5. @{  
  6.    Layout = "~/Views/Shared/_Layout.cshtml";  
  7. }  
  8. <div style="width:60%;height:100%">  
  9.     @(Html.Kendo().Grid<Grid.Models.Company>()  
  10.         .Name("BindGridUsingRead")  
  11.         .Columns(columns =>  
  12.         {  
  13.             columns.Bound(p => p.Id).Width(15).Title("Sr. No.").Filterable(false);  
  14.             columns.Bound(p => p.Name).Title("Name").Width(30).Filterable(false);  
  15.             columns.Bound(p => p.CompanyId).Title("Company Id").Width(15).Filterable(false);  
  16.             })  
  17.            .Scrollable()  
  18.            .Pageable(x => x.PageSizes(new List<object> { 10, 20, 100, 200, 500, "all" }).Refresh(true))  
  19.             .Filterable(ftp => ftp.Mode(GridFilterMode.Row))  
  20.             .Resizable(resize => resize.Columns(true))  
  21.             .HtmlAttributes(new { style = "height: 100%" })  
  22.             .Selectable()  
  23.             .DataSource(dataSource => dataSource  
  24.             .Ajax()  
  25.             .Model(model => model.Id(p => p.Id))  
  26.             .ServerOperation(false)  
  27.             .Read(read => read.Action("BindGrid", "Home"))  
  28.      )  
  29.     )  
  30. </div>  
Step 3

In Controller, write method which will bind the data to Grid by using Ajax Read action method. Now, write some action methods named as BindGrid (to bind the JSON data to Grid). I am going to bind some hard coded values by using action method GetGridData() using Company model which will return IEnumerable List.
  1. public ActionResult Index()  
  2.        {  
  3.            return View();  
  4.        }  
  5.   
  6.        public ActionResult BindGrid([DataSourceRequest]DataSourceRequest request)  
  7.        {  
  8.            try  
  9.            {  
  10.                decimal companyId = 0;  
  11.                List<Models.Company> lst = new List<Models.Company>();  
  12.                lst = GetGridData(Convert.ToInt32(companyId)).ToList();  
  13.                DataSourceResult result = lst.ToDataSourceResult(request, p => new Models.Company  
  14.                {  
  15.                    Id = p.Id,  
  16.                    Name = p.Name,  
  17.                    CompanyId = p.CompanyId,  
  18.                });  
  19.                return Json(result, JsonRequestBehavior.AllowGet);  
  20.            }  
  21.            catch (Exception ex)  
  22.            {  
  23.                var errorMsg = ex.Message.ToString();  
  24.                return Json(errorMsg, JsonRequestBehavior.AllowGet);  
  25.            }  
  26.        }  
  27.       public IEnumerable<Models.Company> GetGridData(decimal companyId)  
  28.        {  
  29.            List<Models.Company> objCmp = new List<Models.Company>();  
  30.            List<Models.Company> listCompany = new List<Models.Company>();  
  31.            objCmp.Add(new Models.Company() { Id = 1, Name = "Rupesh Kahane", CompanyId = 20 });  
  32.            objCmp.Add(new Models.Company() { Id = 2, Name = "Vithal Wadje", CompanyId = 40 });  
  33.            objCmp.Add(new Models.Company() { Id = 3, Name = "Jeetendra Gund", CompanyId = 30 });  
  34.            objCmp.Add(new Models.Company() { Id = 4, Name = "Ashish Mane", CompanyId = 15 });  
  35.            objCmp.Add(new Models.Company() { Id = 5, Name = "Rinku Kulkarni", CompanyId = 18 });  
  36.            objCmp.Add(new Models.Company() { Id = 6, Name = "Priyanka Jain", CompanyId = 22 });  
  37.            if(companyId > 0)  
  38.            {  
  39.                listCompany = objCmp.ToList().Where(a => a.CompanyId <= companyId).ToList();  
  40.                return listCompany.AsEnumerable();  
  41.            }            
  42.            return objCmp.ToList().AsEnumerable();  
  43.        }  
Step 4

Here is the result after running our solution.

 


Scenario II

While working with html controls or forms, there are some situations, like we need to bind the data to Grid on change event of controls or we need to apply some custom filters, on search button click event, we are applying these filters that change the datasource on change event of any html control.

Note

There is a built-in functionality as well to filter Grid data from column values. Here, we are using custom filters.
 
Suppose, the user entered some integer value & we need the data where company id is less than input value in on change event of control. So we take one textbox & will write on change event code into a javascript by using transport.options.read method. We are passing read method URL & input value to out action method.

Step 1

As I explained in scenario I, we are adding only one textbox &JS file which contains change event function to our View. Add some JavaScript code above this which will contain bind grid method as -
  1. <script type="text/javascript">  
  2.     var gridObject;  
  3.     var readURL = new Array();  
  4.     readURL[0] = "/Home/BindGrid";  
  5.     readURL[1] = "/Home/BindGridOnSearch?companyId=";  
  6. </script>  
 Now, our View page will look like the following.
  1. @model Grid.Models.Company  
  2. @using System.Web.Optimization  
  3. @using Kendo.Mvc.UI  
  4. @using Kendo.Mvc.Extensions  
  5. @{  
  6.    Layout = "~/Views/Shared/_Layout.cshtml";  
  7. }  
  8. <script type="text/javascript">  
  9.     var gridObject;  
  10.     var readURL = new Array();  
  11.     readURL[0] = "/Home/BindGrid";  
  12.     readURL[1] = "/Home/BindGridOnSearch?companyId=";  
  13. </script>  
  14. <div>  
  15.     <div class="box-header with-border">  
  16.         <div class="col-xs-12">  
  17.             <div class="col-xs-4 martop" style="text-align:right;width:22%">  
  18.                 @(Html.Kendo().TextBoxFor(model => model.CompanyId)  
  19.                     .Name("CompanyId")  
  20.                     .HtmlAttributes(new { placeholder = "Search By Company Id", @autocomplete = "off", @class = "col-sm-12"style = "width:100%"maxlength = 200 })  
  21.                 )  
  22.             </div>               
  23.         </div>  
  24.     </div>  
  25. </div>  
  26. <br />  
  27.   
  28. <div style="width:60%;height:100%">  
  29.     @(Html.Kendo().Grid<Grid.Models.Company>()  
  30.         .Name("BindGridUsingRead")  
  31.         .Columns(columns =>  
  32.         {  
  33.             columns.Bound(p => p.Id).Width(15).Title("Sr. No.").Filterable(false);  
  34.             columns.Bound(p => p.Name).Title("Name").Width(30).Filterable(false);  
  35.             columns.Bound(p => p.CompanyId).Title("Company Id").Width(15).Filterable(false);  
  36.             })  
  37.            .Scrollable()  
  38.            .Pageable(x => x.PageSizes(new List<object> { 10, 20, 100, 200, 500, "all" }).Refresh(true))  
  39.             .Filterable(ftp => ftp.Mode(GridFilterMode.Row))  
  40.             .Resizable(resize => resize.Columns(true))  
  41.             .HtmlAttributes(new { style = "height: 100%" })  
  42.             .Selectable()  
  43.             .DataSource(dataSource => dataSource  
  44.             .Ajax()  
  45.             .Model(model => model.Id(p => p.Id))  
  46.             .ServerOperation(false)  
  47.             .Read(read => read.Action("BindGrid", "Home"))  
  48.      )  
  49.     )  
  50. </div>  
  51. <script src="~/Scripts/Custom/Home.js"></script>  
Step 2

Now, write code on change event of textbox into JavaScript Home.js file. In our JS file on windows.load method, we can get data of Grid into a our global variable.
  1. $(window).load(function () {  
  2.     gridObject = $("#BindGridUsingRead").data("kendoGrid");  
  3. });  
  4.   
  5. $(document).ready(function () {     
  6.     $('#CompanyId').on('change'function () {     
  7.         //debugger;  
  8.         var cmpId = $("input[id='CompanyId']").val();  
  9.         gridObject.dataSource.transport.options.read.url = readURL[1] + cmpId;  
  10.         gridObject.dataSource.read();  
  11.     });  
  12. });  
Step 3

Write some code into Controller against these read methods.
  1. public ActionResult BindGridOnSearch([DataSourceRequest]DataSourceRequest request, string companyId)  
  2.         {  
  3.             try  
  4.             {  
  5.                 List<Models.Company> list = new List<Models.Company>();  
  6.                 list = GetGridData(Convert.ToInt32(companyId)).ToList();  
  7.                 DataSourceResult result = list.ToDataSourceResult(request, p => new Models.Company  
  8.                 {  
  9.                     Id = p.Id,  
  10.                     Name = p.Name,  
  11.                     CompanyId = p.CompanyId,  
  12.                 });  
  13.                 return Json(result, JsonRequestBehavior.AllowGet);  
  14.             }  
  15.             catch (Exception ex)  
  16.             {  
  17.                 var errorMsg = ex.Message.ToString();  
  18.                 return Json(errorMsg, JsonRequestBehavior.AllowGet);  
  19.             }  
  20.         }  
Step 4

Here is the result after running our solution (if we enter 25 into input box).

 
 
Summary

In this article, you learned the basics of how to bind data to Kendo Grid in MVC using multiple methods.