Monday, June 18, 2012

Telerik MVC 3 grid - Custom binding

In this post, I will try to explain how to enable custom binding  of Telerik MVC grid in MVC 3 application.
There are two ways to bind  Telerik MVC grid for custom binding. Server binding and Ajax binding.


Custom binding with server settings:

Binding the grid with EnableCustomBinding = true means,  the data sorting and paging for the grid will be handled from the custom code, in other words for MVC, from the controller action or  from the Provider class or database. The controller action will return only the current page data instead of returning whole bunch of data.
Lets say, we have a list of Student which we want to show in the grid with pagination and sorting enabled.
For this, let us define our Student Model:

//Student.cs class

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

namespace CustomGridBindingExample.Models
{
    public class Student
    {
        public string Name { get; set; }
        public int RollNo { get; set; }
        public DateTime DOB { get; set; }
        public string Session { get; set; }
    }
}

The  grid settings in view is as follows:

 //View design
//CustomServerBinding.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<List<CustomGridBindingExample.Models.Student>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Custom Server Binding
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<h2>Telerik Grid - Custom Server Binding Example -  Server setting. </h2>
View action and grid action are same.
<br />
<fieldset>  
    <legend>Grid Sample </legend>
    <%= Html.Telerik().Grid < CustomGridBindingExample.Models.Student>()
           .Name("Grid")
           .BindTo(Model)
           .EnableCustomBinding(true)
                           .DataBinding(databinding => databinding.Server().Select("CustomServerBinding", "Student"))
           .Columns(colums =>
           {
               colums.Bound(model => model.Name);
               colums.Bound(model => model.Session);
               colums.Bound(model => model.DOB);
           })
           .Pageable(settings => settings.Total((int)ViewData["total"]))       
           .Sortable()
            %>
</fieldset>
</asp:Content>

Not the Model that is passed to view is List<<CustomGridBindingExample.Models.Student>. The model should be a list or Enumerable type.
For custom binding, EnableCustomBinding(true) is set and for Pageable, Total((int)ViewData["total"]) is set.
Setting the Total value is necessary to correctly displaying the pagination. 

Now take a look at the controller action:


Controller Actions:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;
using System.Collections;
using CustomGridBindingExample.Models;
namespace CustomGridBindingExample.Controllers
{
    public class StudentController : Controller
    {
       
        public ActionResult Index()
        {  
            return View();
        }
        //This method will be called for binding the grid.
        [GridAction(GridName = "Grid")]
        public ActionResult CustomServerBinding(GridCommand command)
        {          
          // command object holds paging and sorting information, so use it for paging and sorting.
            IList<Student> data = GetServerData(!IsEmptyCommand(command) ? command : new GridCommand());          
            return View(data);
        }
    
        private IList<Student> GetServerData(GridCommand gridCommand)
        {
            IList<Student> students= new List<Student>();
         // Return data from database using the paging and sorting information.
            for (int i = 1; i <= 10000; i++)
            {
                students.Add(new Student() { Name = "Mahatab - " + i.ToString(), DOB = DateTime.Parse("11/25/1982").AddDays(i), Session = "1999-2000", RollNo = 4318 });
            }
            ViewData["total"] = students.Count; // Or get the count from database.
            //Made custom pagination here, for real application, you should do it from server.
            var returnList = students.Skip((gridCommand.Page - 1) * gridCommand.PageSize).Take(gridCommand.PageSize).ToList();
            return returnList;
        }
        private bool IsEmptyCommand(GridCommand command)
        {
            return command.PageSize == 0;
        }

    }
}

Thats all, your code should work for paging and sorting.

 

Custom binding with Ajax settings:

 For custom binding with Ajax setting, the grid setting is as follows:

 <%= Html.Telerik().Grid < CustomGridBindingExample.Models.Student>()
           .Name("Grid")
           .EnableCustomBinding(true)
           .DataBinding(databinding => databinding.Ajax().Select("_CustomBindingClient", "Student"))
           .Columns(colums =>
           {
               colums.Bound(model => model.Name);
               colums.Bound(model => model.Session);
               colums.Bound(model => model.DOB);
           })
           .Pageable()       
          
            %>

And the controller action code looks like:

      [GridAction(EnableCustomBinding = true)]
        public ActionResult _CustomBindingClient(GridCommand command)
        {
            IEnumerable data = GetServerData(command);
            return View(new GridModel
            {
                Data = data,
                Total = (int)ViewData["total"]
            });
        }

Your grid should work fine.


No comments:

Post a Comment