Adding a Kendo Grid in MVC project (Kendo UI For MVC)

Adding a Kendo Grid in MVC project (Kendo UI For MVC)



In order to use kendo grid we need to have some files.

1. Kendo.mvc.dll


2.  js files(kendo.all.min.js , kendo.aspnetmvc.min.js)

3. Content files


Folder with a name 2018.3.911

All above files can either be downloaded from nuget package or trial version which is offer by kendo ui website.

Note: Kendo is paid plugin so without getting the trial version you wont be able to access all those files.
  
Kendo works on helpers which are provided for MVC environment.

Follow below steps in order a add basic grid to your mvc project.


Step 1. Add all the dll and files mentioned above.

Step 2. Add the reference of all files in layout.cstml

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    <!--Kendo UI combined JavaScript -->
    <link href="~/Content/Kendo/2018.3.911/kendo.common.min.css" rel="stylesheet" />
    <!-- (Optional) RTL CSS for Kendo UI widgets for the web. Include only in right-to-left applications. -->
    <link href="~/Content/Kendo/2018.3.911/kendo.rtl.min.css" rel="stylesheet" type="text/css" />
    <!-- Default Kendo UI theme CSS for web widgets and widgets for data visualization. -->
    <link href="~/Content/Kendo/2018.3.911/kendo.default.min.css" rel="stylesheet" />
    <!-- (Optional) Kendo UI Hybrid CSS. Include only if you will use the mobile devices features. -->
    <link href="~/Content/Kendo/2018.3.911/kendo.default.mobile.min.css" rel="stylesheet" type="text/css" />
    <link href="~/Scripts/kendo/all.css" rel="stylesheet" type="text/css" />
</head>

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

//Kendo reference starts from here
    <script src="~/Scripts/Kendo/js/kendo.all.min.js"></script>
    <script src="~/Scripts/Kendo/js/kendo.aspnetmvc.min.js"></script>
    <script type="text/javascript">
    @Html.Kendo().DeferredScriptsFor("PestListGridManagement", false);
    </script>
</body>

Full Layout file code

@using Kendo.Mvc.UI
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

    <!--Kendo UI combined JavaScript -->
    <link href="~/Content/Kendo/2018.3.911/kendo.common.min.css" rel="stylesheet" />
    <!-- (Optional) RTL CSS for Kendo UI widgets for the web. Include only in right-to-left applications. -->
    <link href="~/Content/Kendo/2018.3.911/kendo.rtl.min.css" rel="stylesheet" type="text/css" />
    <!-- Default Kendo UI theme CSS for web widgets and widgets for data visualization. -->
    <link href="~/Content/Kendo/2018.3.911/kendo.default.min.css" rel="stylesheet" />
    <!-- (Optional) Kendo UI Hybrid CSS. Include only if you will use the mobile devices features. -->
    <link href="~/Content/Kendo/2018.3.911/kendo.default.mobile.min.css" rel="stylesheet" type="text/css" />
    <link href="~/Scripts/kendo/all.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

    <script src="~/Scripts/Kendo/js/kendo.all.min.js"></script>
    <script src="~/Scripts/Kendo/js/kendo.aspnetmvc.min.js"></script>
    <script type="text/javascript">
    @Html.Kendo().DeferredScriptsFor("PestListGridManagement", false);
    </script>
</body>
</html>

Step 3: Add code in view to intialize the grid.

@using Kendo.Mvc.UI
@model IEnumerable<KendoGridMVCEx.Models.Pest>
@{
    ViewBag.Title = "Home Page";
}

<div class="row">
    <div class="col-md-12">
@(Html.Kendo().Grid(Model)
    .Name("SampleGrid")
    .Columns(columns =>
    {

        columns.Bound(p => p.PestName).Title("Pest name <span class='k-icon k-i-kpi'></span>");
        columns.Bound(p => p.PestId);
        columns.Bound(p => p.NumberOfCountriesPresent).Title("Number<br/>of<br/>countries<br/>where<br/>present <span class='k-icon k-i-kpi'></span>").Filterable(false);
    })
    .Filterable(filterable => filterable
    .Extra(false)
    .Operators(operators => operators
    .ForString(str => str.Clear()
        .StartsWith("Starts with")
        .IsEqualTo("Is equal to")
        .IsNotEqualTo("Is not equal to")
        .Contains("Contains")
    ))
    )
                .DataSource
                (
                    dataSource => dataSource
                    .Ajax()
                    .PageSize(25)
                        // .Read(read => read.Action("GetGridData", "Home", new { sessionid = ViewContext.RouteData.Values["sessionid"], showIncluded = false, isManagement = true }))
                        .Read(read => read.Action("GridData", "Home").Type(HttpVerbs.Post))
                    .Model(model => model.Id(p => p.PestId))
                )
                .Filterable()
                .Sortable()
                .Pageable
                (
                    pager => pager
                    .Input(true)
                    .Numeric(false)
                    .Info(false)
                    .PreviousNext(true)
                    .Refresh(false)
                    .PageSizes(false)
                )
                .NoRecords("No Pests for risk management")
    .Deferred()
            //.Events
            //(
            //    events => events
            //        .DataBound("ManagementDataBound")
            //)
            )

    </div>
</div>

Step 4: Add model which will be bind to grid.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace KendoGridMVCEx.Models
{
    public class Pest
    {
        public int PestId { get; set; }
        public int FormId { get; set; }
        public string PestType { get; set; }
        public string PestName { get; set; }
        //public YesNo OnCrop { get; set; }
        //public CommodityTypeYesNo OnCommodity { get; set; }
        public string OnCommodityDisplayName { get; set; }
        //public PresentAbsent ExportingCountry { get; set; }
        //public PresentAbsent ImportingCountry { get; set; }
        public int NumberOfCountriesPresent { get; set; }
        public int? PqStatus { get; set; }
        //public CompleteIncomplete RiskAssesment { get; set; }
        public string RiskAssesmentDisplayName { get; set; }
        //public RiskManagementStatus RiskManagement { get; set; }
        public string RiskManagementDisplayName { get; set; }
        public string Notes { get; set; }
        //public YesNo HasUserModified { get; set; }
        //public YesNo? RequiresPhytosanitaryMeasures { get; set; }
        public int DatasheetId { get; set; }
        public int IncludeExcludeStatusId { get; set; }
        public int? IncludeExcludeReasonId { get; set; }
        public string ExcludeNotes { get; set; }
    }
}

Step 5: Add Action method which will be used to make ajax call to fetch data. Grid data in our case.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using KendoGridMVCEx.Models;

namespace KendoGridMVCEx.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
        [HttpPost]
        public ActionResult GridData([DataSourceRequest] DataSourceRequest request)
        {
            var model = new List<Pest>
            {
                new Pest() {PestId = 12, PestName = "My Pest12"},
                new Pest() {PestId = 13, PestName = "My Pest13"},
                new Pest() {PestId = 14, PestName = "My Pest14"},
            };
            return Json(model.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }
    }
}

Step 6: Sometime kendo is able to find any refernce files while intialize it. So in order to overcome that we use deffered loading.


   .Deferred() in the last of the grid.
And also we need to add a reference in layout so that it can be intialized with deffered keyword.
So in layout we need to add DeferredScriptsFor after the reference of kendo grid.

    <script src="~/Scripts/Kendo/js/kendo.all.min.js"></script>
    <script src="~/Scripts/Kendo/js/kendo.aspnetmvc.min.js"></script>


    <script type="text/javascript">
    @Html.Kendo().DeferredScriptsFor("SampleGrid", false);
    </script>

Final Output


[HttpPost]
        public ActionResult GridData([DataSourceRequest] DataSourceRequest request)
        {
            var model = new List<Pest>
            {
                new Pest() {PestId = 12, PestName = "My Pest12"},
                new Pest() {PestId = 13, PestName = "My Pest13"},
                new Pest() {PestId = 14, PestName = "My Pest14"},
            };
            return Json(model.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

Share on Google Plus

About myzingonline

Myzingonline is all about zing to share experience, knowledge, likes, dislikes and ideas of a person to the world.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment