Multiple Ways To Bind Data To Kendo Grid In MVC

Introduction

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

What is Kendo Grid?

The Kendo UI Grid is a powerful widget that 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 the AJAX Read action method.

Scenario II

Change the data source on the change event of any HTML controls.

Scenario I

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

This read method is the Action Result method in MVC which will return JSON DataSourceResult & directly bind the data to Grid.

Note. Also, the developer can pass parameters to this read method. Suppose below is our read method.

Read(read => read.Action("BindGrid", "Home").Data("SortByCompanyId"))

In the above line, my JavaScript function name is SortByCompanyId which will return the company ID. On that basis, we can pass parameters to our action method in the Controller.

Our JavaScript function is like the following.

<script type="text/javascript">
    function SortByCompanyId() {
        var cId = 25;
        return {
            companyId: cId
        }
    }
</script>

Step 1. Create a Model, give it a name as a Company, and declare some properties into it.

public class Company
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? CompanyId { get; set; }
}

Step 2. Now, create a Controller, and give it a name as HomeController. In this, create an 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.

@model Grid.Models.Company
@using System.Web.Optimization
@using Kendo.Mvc.UI
@using Kendo.Mvc.Extensions
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div style="width:60%;height:100%">
    @(Html.Kendo().Grid<Grid.Models.Company>()
        .Name("BindGridUsingRead")
        .Columns(columns =>
        {
            columns.Bound(p => p.Id).Width(15).Title("Sr. No.").Filterable(false);
            columns.Bound(p => p.Name).Title("Name").Width(30).Filterable(false);
            columns.Bound(p => p.CompanyId).Title("Company Id").Width(15).Filterable(false);
        })
        .Scrollable()
        .Pageable(x => x.PageSizes(new List<object> { 10, 20, 100, 200, 500, "all" }).Refresh(true))
        .Filterable(ftp => ftp.Mode(GridFilterMode.Row))
        .Resizable(resize => resize.Columns(true))
        .HtmlAttributes(new { style = "height: 100%" })
        .Selectable()
        .DataSource(dataSource => dataSource
            .Ajax()
            .Model(model => model.Id(p => p.Id))
            .ServerOperation(false)
            .Read(read => read.Action("BindGrid", "Home"))
        )
    )
</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 the action method GetGridData() using the Company model which will return an IEnumerable List.

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

public ActionResult BindGrid([DataSourceRequest] DataSourceRequest request)
{
    try
    {
        decimal companyId = 0;
        List<Models.Company> lst = new List<Models.Company>();
        lst = GetGridData(Convert.ToInt32(companyId)).ToList();
        DataSourceResult result = lst.ToDataSourceResult(request, p => new Models.Company
        {
            Id = p.Id,
            Name = p.Name,
            CompanyId = p.CompanyId,
        });
        return Json(result, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        var errorMsg = ex.Message.ToString();
        return Json(errorMsg, JsonRequestBehavior.AllowGet);
    }
}

public IEnumerable<Models.Company> GetGridData(decimal companyId)
{
    List<Models.Company> objCmp = new List<Models.Company>();
    List<Models.Company> listCompany = new List<Models.Company>();
    objCmp.Add(new Models.Company() { Id = 1, Name = "Rupesh Kahane", CompanyId = 20 });
    objCmp.Add(new Models.Company() { Id = 2, Name = "Vithal Wadje", CompanyId = 40 });
    objCmp.Add(new Models.Company() { Id = 3, Name = "Jeetendra Gund", CompanyId = 30 });
    objCmp.Add(new Models.Company() { Id = 4, Name = "Ashish Mane", CompanyId = 15 });
    objCmp.Add(new Models.Company() { Id = 5, Name = "Rinku Kulkarni", CompanyId = 18 });
    objCmp.Add(new Models.Company() { Id = 6, Name = "Priyanka Jain", CompanyId = 22 });
    if (companyId > 0)
    {
        listCompany = objCmp.ToList().Where(a => a.CompanyId <= companyId).ToList();
        return listCompany.AsEnumerable();
    }            
    return objCmp.ToList().AsEnumerable();
}

Step 4. Here is the result after running our solution.

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 the search button click event, we are applying these filters that change the data source 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 the company id is less than the input value in on change event of the control. So we take one textbox & will write on change event code into a javascript by using transport. options. read method. We are passing the read method URL & input value to our action method.

Step 1. As I explained in the scenario I, we are adding only one textbox &JS file which contains the change event function to our View. Add some JavaScript code above this which will contain the bind grid method.

<script type="text/javascript">
    var gridObject;
    var readURL = new Array();
    readURL[0] = "/Home/BindGrid";
    readURL[1] = "/Home/BindGridOnSearch?companyId=";
</script>

Now, our View page will look like the following.

@model Grid.Models.Company
@using System.Web.Optimization
@using Kendo.Mvc.UI
@using Kendo.Mvc.Extensions

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script type="text/javascript">
    var gridObject;
    var readURL = new Array();
    readURL[0] = "/Home/BindGrid";
    readURL[1] = "/Home/BindGridOnSearch?companyId=";
</script>

<div>
    <div class="box-header with-border">
        <div class="col-xs-12">
            <div class="col-xs-4 martop" style="text-align:right;width:22%">
                @(Html.Kendo().TextBoxFor(model => model.CompanyId)
                    .Name("CompanyId")
                    .HtmlAttributes(new { placeholder = "Search By Company Id", @autocomplete = "off", @class = "col-sm-12", style = "width:100%", maxlength = 200 })
                )
            </div> 
        </div>
    </div>
</div>
<br />

<div style="width:60%;height:100%">
    @(Html.Kendo().Grid<Grid.Models.Company>()
        .Name("BindGridUsingRead")
        .Columns(columns =>
        {
            columns.Bound(p => p.Id).Width(15).Title("Sr. No.").Filterable(false);
            columns.Bound(p => p.Name).Title("Name").Width(30).Filterable(false);
            columns.Bound(p => p.CompanyId).Title("Company Id").Width(15).Filterable(false);
        })
        .Scrollable()
        .Pageable(x => x.PageSizes(new List<object> { 10, 20, 100, 200, 500, "all" }).Refresh(true))
        .Filterable(ftp => ftp.Mode(GridFilterMode.Row))
        .Resizable(resize => resize.Columns(true))
        .HtmlAttributes(new { style = "height: 100%" })
        .Selectable()
        .DataSource(dataSource => dataSource
            .Ajax()
            .Model(model => model.Id(p => p.Id))
            .ServerOperation(false)
            .Read(read => read.Action("BindGrid", "Home"))
        )
    )
</div>

<script src="~/Scripts/Custom/Home.js"></script>

Step 2. Now, write code on the change event of the textbox into the JavaScript Home.js file. In our JS file on Windows.load method, we can get data of Grid into our global variable.

$(window).load(function () {
    gridObject = $("#BindGridUsingRead").data("kendoGrid");
});

$(document).ready(function () {     
    $('#CompanyId').on('change', function () {     
        //debugger;   
        var cmpId = $("input[id='CompanyId']").val();   
        gridObject.dataSource.transport.options.read.url = readURL[1] + cmpId;
        gridObject.dataSource.read();
    });
});

Step 3. Write some code into the Controller against these read methods.

public ActionResult BindGridOnSearch([DataSourceRequest] DataSourceRequest request, string companyId)
{
    try
    {
        List<Models.Company> list = new List<Models.Company>();
        list = GetGridData(Convert.ToInt32(companyId)).ToList();
        DataSourceResult result = list.ToDataSourceResult(request, p => new Models.Company
        {
            Id = p.Id,
            Name = p.Name,
            CompanyId = p.CompanyId,
        });
        return Json(result, JsonRequestBehavior.AllowGet);
    }
    catch (Exception ex)
    {
        var errorMsg = ex.Message.ToString();
        return Json(errorMsg, JsonRequestBehavior.AllowGet);
    }
}

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

Result

Summary

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


Similar Articles