Telerik RadGrid Client Side Binding Using JavaScript

Before going to start about the code, I would like to tell you something about Telerik. Well, Telerik adds magic in our application. Its a third party tool that enhances the functionality of asp.net. If you have never used telerik and want to know more, I would suggest you to go through below links:-
http://www.telerik.com/
http://visualstudiogallery.msdn.microsoft.com/05896521-cda2-4c2e-9f5d-e562fe5059b0

In this article I am going to tell you, how to bind Telerik RAD grid using java script.

This article is the cocktail of asp.net, javascript and Telerik Controls

Software Requirement:
Microsoft Visual studio 2010.
Telerik dll (It is paid, don’t get panic. You can use 30 days trial)

In this article, I am using a scenario where I have to bind a telerik rad grid with columns Employee ID , Employee Name and Employee Address. And this will happen, when I click a button “Show Data”. I have added another rad control Rad Notification.

Now, let me tell you about the code.

Lets add the telerik dll into your project first and then add a page “Demo.aspx” into your project. and then add Demo.js in scripts folder.

Design (Demo.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo.aspx.cs" Inherits=”WebPractice.Demo" %>

<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<head id="Head1" runat="server">
 <title>My demo </title>
 <div id="dvhead" runat="server">
 <script src="../Scripts/Demo.js" type="text/javascript"></script>
 </div>

</head>

<body>
<form id="form1" runat="server">
 <telerik:RadScriptManager ID="scriptManager" runat="server" AsyncPostBackTimeout="1200" EnablePageMethods="true"
 OutputCompression="Forced" EnableScriptCombine="true" EnableViewState="false"></telerik:RadScriptManager>

<telerik:RadAjaxManager ID="rdAjaxManager" runat="server">

 <AjaxSettings>
 <telerik:AjaxSetting AjaxControlID="rdAjaxPanel">
 <UpdatedControls>
 <telerik:AjaxUpdatedControl ControlID="dvMain" LoadingPanelID="rdAjaxLoadingPanel" />
 </UpdatedControls>
 </telerik:AjaxSetting>
 </AjaxSettings>

 </telerik:RadAjaxManager>

 <telerik:RadAjaxLoadingPanel ID="rdAjaxLoadingPanel" runat="server" Skin="Windows7" ZIndex="3000" />

<telerik:RadWindowManager ID="RadWindowManager1" runat="server" >
 </telerik:RadWindowManager>

 <telerik:RadAjaxPanel runat="server" ID="rdAjaxPanel">

<div id="dvMain" runat="server">
<asp:HiddenField ID="hdnPageSize" runat="server" />
<asp:HiddenField ID="hdnPageNumber" runat="server" />

<!--In Demo.aspx I have a AnchorTag that call the grid Bind: -->
<a href="javascript: void(0);" onclick="javascript:ShowEmployeeData();">Show Data</a>


<!--My Grid Structure is this: -->

<telerik:RadGrid ID="rgEmployeeData" runat="server" AutoGenerateColumns="False" EnableLinqExpressions="false"
 AllowFilteringByColumn="false" AllowPaging="True" HeaderStyle-Font-Bold="true"
 ShowHeaderWhenEmpty="true" ShowFooter="false" AllowSorting="false" PageSize="100" Width="100%" Font-Size="11px"
 Skin="Windows7" CssClass="sf_grid" AllowCustomPaging="true" >
 <PagerStyle Mode="NextPrevAndNumeric" AlwaysVisible="true"></PagerStyle>

 <MasterTableView EditMode="InPlace" TableLayout="Auto" AutoGenerateColumns="false" CommandItemDisplay="None" >



 <Columns>

<telerik:GridBoundColumn HeaderText=" Empoyee ID" UniqueName="EmpoyeeID" DataField="EmpoyeeID" ></telerik:GridBoundColumn>

<telerik:GridBoundColumn HeaderText="Employee Name <span class='icon-arrow'></span>" UniqueName="EmployeeName" DataField="EmployeeName" ></telerik:GridBoundColumn>

<telerik:GridBoundColumn HeaderText=" Employee Address" UniqueName="EmployeeAddress" DataField="EmployeeAddress" ></telerik:GridBoundColumn>

 </telerik:GridTemplateColumn>
</Columns>

</MasterTableView>

<ClientSettings>

<ClientEvents OnCommand="rgEmployeeData_Command" />
 <Resizing AllowColumnResize="True" AllowRowResize="false" ResizeGridOnColumnResize="true"
 ClipCellContentOnResize="true" EnableRealTimeResize="false" AllowResizeToFit="true" />
</ClientSettings>

 </telerik:RadGrid>

</div>
 <telerik:RadNotification ID="WaitIconNotification" runat="server" VisibleOnPageLoad="false"
 Position="Center" Width="300" Height="125" Title="Wait"
 Value="~/" Skin="Office2007" EnableRoundedCorners="true" AutoCloseDelay="0">
 <ContentTemplate>
 Wait page is loading......
 </ContentTemplate>
 </telerik:RadNotification>

</telerik:RadAjaxPanel>
 </form>
</body>
</html>

Java Script (Demo.js)

function ShowEmployeeData() {
 var WaitIconNotification = $find('WaitIconNotification');

 var hdnPageSize = document.getElementById('hdnPageSize');// get page Size
 var hdnPageNumber = document.getElementById('hdnPageNumber');//get Page Number

 var tableView = $find('rgEmployeeData').get_masterTableView();
 hdnPageSize.value = tableView.get_pageSize();
 hdnPageNumber.value = 1;
 WaitIconNotification.show();
 PageMethods.GetGridData(tableView.get_pageSize(),1,updateGrid);
}


function updateGrid(result) {
 var WaitIconNotification = $find('WaitIconNotification');
 var tableView = $find('rgEmployeeData').get_masterTableView();
 tableView.set_dataSource(result["Data"]);
 tableView.dataBind();
 tableView.set_virtualItemCount(parseInt(result["Count"]));
 WaitIconNotification.hide();
}

//this function is called for paging and page size change event
function rgEmployeeData_Command(sender, args) {
 args.set_cancel(true);
 var hdnPageSize = document.getElementById('hdnPageSize');
 var hdnPageNumber = document.getElementById('hdnPageNumber');
 var currentPageIndex = sender.get_masterTableView().get_currentPageIndex();
 var pageSize = sender.get_masterTableView().get_pageSize();
 //for page Index and Page Number
 hdnPageSize.value = pageSize;
 hdnPageNumber.value = currentPageIndex + 1;
 WaitIconNotification.show();
 PageMethods.GetGridData(pageSize, currentPageIndex + 1, updateGrid);
}

Code behind (Demo.aspx.cs)
Here we will add a web method.

using System;
using System.Collections.Generic;
using System.Web.Services;

namespace WebPractice
{
 public partial class Demo : System.Web.UI.Page
 {
 protected void Page_Load(object sender, EventArgs e)
 {

 }

//This is the main Function this web method will be called by Java script
 [WebMethod]
 public static Dictionary<string, object> GetGridData( int pageSize, int pageIndex)
 {

 var listData = new Dictionary<string, object>();
 var listItems = new List<object>();
 // here u can get the Data from DB here I am using 3 rows

 //here I am not using Any Database for Demo so the Variable Page Size and Page Number are not being used. But in real case scenario we should use these to get the data
 listItems.Add(new { EmployeeID = 1, EmployeeName = "Vipin Joshi", EmployeeAddress = "Mindfire India" });
 listItems.Add(new { EmployeeID = 2, EmployeeName = "Anand", EmployeeAddress = "Mindfire India" });
 listItems.Add(new { EmployeeID = 3, EmployeeName = "Narendra", EmployeeAddress = "Mindfire India" });

 listData.Add("Data", listItems);
 listData.Add("Count", listItems.Count);

 return listData;
 }
 }
}

This is all about the design and code.

The motive of using client site binding is to improve performance of the page by reducing post backs.

Here in my code, I have used two hidden fields. You might have question “why we are using hidden fields”. Well the reason is quite simple if you need to apply post back in the page and if you need to set page size or page number then you can use these hidden fields values.
So if we need a post back then just call a java script function inside the event. Like below:

protected void btnCheckPostback_Click(object sender, EventArgs e)
{
 ScriptManager.RegisterStartupScript(this, typeof(Page), "", "BindEmployeeData();",
 true);
}

function BindEmployeeData() {
 var WaitIconNotification = $find('WaitIconNotification');
 var hdnPageSize = document.getElementById('hdnPageSize');// get page Size
 var hdnPageNumber = document.getElementById('hdnPageNumber');//get Page Number
 var tableView = $find('rgEmployeeData').get_masterTableView();
 WaitIconNotification.show();
 PageMethods.GetGridData(parseInt(hdnPageSize.value),parseInt(hdnPageNumber.value),updateGrid);
}

Hope it help you. Please add your comments below, if you have any query.

Written By: Vipin Joshi, ASP.Net Developer, Mindfire Solutions

Advertisements

Posted on January 29, 2014, in ASP.Net, Javascript and tagged , , , , , , , , , , , . Bookmark the permalink. Leave a comment.

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

%d bloggers like this: