ASP.NET Ajax Grid and Pager
Published: 31 May 2007
Last Updated: 06 June 2007
By: Kazi Manzur Rashid
Complex control development with the Microsoft ASP.NET AJAX platform.
Introduction
This article will show you how to create an AJAX Grid and a generic pager, which mimics the built-in GridView control on the client side.
Features
The Control(s) Provides:
- Able to bind to any web service call that returns an array.
- A GridView like API on the client side.
- Able to AutoGenerate Columns based upon the dataSource.
- Support for Sorting and Paging where developer can spawn his/her own logic.
- Full VS Design Time Support.
- Supports Column Drag and Drop.
- Compatible with all major browsers including IE, Firefox, Opera and Safari.
Prerequiste
This is not a beginner’s guide. If you are new to ASP.NET AJAX or not familiar with Client-Centric or Server-Centric Development model, I strongly recommend you visit http://ajax.asp.net. To run the solution you must have:
- Visual Studio 2005 or Visual Web Developer.
- Latest Version (v1.0) of ASP.NET AJAX.
- SQL Server 2005 (At least Express Edition) for running the sample.
- Northwind Database (You can download the sql script from here).
Background
ASP.NET AJAX is a great platform to develop rich user experience web applications. The most amazing part is that it replaces the traditional page postback refresh model. We can easily add an UpdatePanel
(A Part of Server Centric Development model) in the updatable part of a page to remove the regular page postback. But the problem with an UpdatePanel
is that it not only returns the updated data but also returns the HTML tags of that updated part. This is not an issue if you are developing small or mid size applications where performance and network bandwidth is not a concern. However if you are developing a large system where performance and network bandwidth matters, then definitely you want to send only the updated data without the unnecessary HTML tags.
When developing a database application it is a common requirement to show data in a tabular format with sorting and paging. ASP.NET has two first class controls for this purpose, the DataGrid
and the GridView
. But the problem with these controls there is no object model in the client side, which we can utilize with JavaScript
. There is no way we can call a Web Service or Server side method and bind the result with it in the client side. Developers often have to write reparative DHTML code to render the tabular data.
The AJAX Grid
The provided AJAX Grid
solves the above problem. Developer can easily bind the result of a Web Service or Server Side method calls in the client side. It also exposes a similar API like DataGrid/GridView
in client side that most of the ASP.NET developers are already familiar with.
Data Binding
When binding data we set the DataSource
of the target control and call the DataBind()
method. The same steps are required for the AJAX Grid
. The following lines show the Suppliers
table records from the Northwind database.
Code Listing 1: JavaScript
- <script type="text/javascript">
- function pageLoad()
- {
- var grid = $find('grid'); // Get the reference of the Client Side Component
- DataService.GetAllSupplier
- (
- function(suppliers)
- {
- grid.set_dataSource(suppliers);
- grid.dataBind();
- }
- );
- }
Code Listing 2: AJAX
- <asp:ScriptManager ID="TheScriptManager" runat="server">
- <Services>
- <asp:ServiceReference Path="~/DataService.asmx" />
- </Services>
- </asp:ScriptManager>
- <ajax:Grid ID="grid1" runat="server"></ajax:Grid>
Figure 1: Output
This is a simple page, which uses a ScriptManager
with a WebService reference and an AJAX Grid
. In the pageLoad()
(A special event which is fired by the ASP.NET AJAX Library every time the page is loaded) event we are getting the reference of the AJAX Grid
by using the $find
method (A shortcut method to find the Client Side Component, please do not confuse Client Side Component with regular DOM
element, to get a DOM
element reference use $get
) statements and then we are setting the dataSource
that the web service call returns and finally calls the dataBind()
method. As you can see, the output is the same as we would set up a DataGrid/GridView
with the default setting.
Styling
The above example shows the data in a plain vanilla style, certainly we do not want show the data in this way rather we would like to add some styling property. AJAX Grid similarly exposes CssClass
, HeaderCssClass
, RowCssClass
, AlternatingRowCssClass
and SelectedRowCssClass
to do the same styling as the DataGid/GridView
controls. Once we apply these styles the above example output looks like the following.
Figure 2: Output with Styles
The Supplier.aspx of the attached sample has full source code of the above two examples.
The Column Collection
When showing the tabular data we certainly like to add more control such as hiding a column, showing a different header text, alignment, allow sorting, setting column width etc. In AJAX Grid
we can easily define the column collection in declarative model like the following:
Code Listing 3: AJAX Grid with Columns
- <ajax:Grid ID="grid" runat="server" CssClass="grid" HeaderCssClass="gridHeader"
- RowCssClass="gridRow" AlternatingRowCssClass="gridAltRow" SortColumn="CompanyName"
- SortOrderAscendingImage="Images/up.gif" SortOrderDescendingImage="Images/dn.gif">
- <Columns>
- <ajax:GridColumn DataField="CompanyName" HeaderText="Company" Sortable="True"
- Nowrap="True"/>
- <ajax:GridColumn DataField="ContactTitle" HeaderText="Title" Sortable="True"/>
- <ajax:GridColumn DataField="ContactName" HeaderText="Contact" Sortable="True"/>
- <ajax:GridColumn DataField="Address" HeaderText="Address" Sortable="True"/>
- <ajax:GridColumn DataField="City" HeaderText="City" Sortable="True" />
- <ajax:GridColumn DataField="PostalCode" HeaderText="Postal Code" Sortable="True"
- Nowrap="True"/>
- <ajax:GridColumn DataField="Country" HeaderText="Country" Sortable="True" />
- <ajax:GridColumn DataField="Phone" HeaderText="Phone" Sortable="True"/>
- </Columns>
- </ajax:Grid>
The AJAX Gird Column
contains the following important properties:
HeaderText
: Same as in theDataGrid/GridView
.DataField
: Same as in theDataGrid/GridView
.Sortable
: Iftrue,
the header text will be displayed as a hyperlink instead of text.SortField
: Must be specified ifSortField
is different fromDataField
.FormatString
: Same as in theDataGrid/GridView
.
Sorting
The AJAX Grid
also supports sorting in the same way as the DataGrid/GridView
control. When a column
header is clicked it raises the Sort
event, which we have to subscribe. To show the current sort order we have to set the SortOrderAscendingImage
and SortOrderDescendingImage
property of AJAX Grid
. In order to get the current sort column and order we can check the SortColumn
and SortOrder
property. The following shows how to add sorting support in the AJAX Grid
which shows the Customers
table of Northwind database.
Code Listing 4: AJAX Grid with Columns
- function pageLoad()
- {
- // Getting the reference of the Client Components and
- // attaching the event handlers
- _grid = $find('grid');
- _grid.add_sort(sorted);
- }
- function sorted(sender, e)
- {
- // Set the SortColum and SortOrder of the Grid so
- // that it can properly render current sort column and
- // and the associated image
- _grid.set_sortColumn(e.get_sortColumn());
- _grid.set_sortOrder(e.get_sortOrder());
- // Here we can call the WebService with the new SortColumn and SortOrder
- }
Figure 3: AJAX Grid Sorted
The Customer.aspx of the attached sample has the full source code of the sorting example.
Selecting/Deleting Rows
To show the Select
and Delete
link like in the DataGrid/GridView
we have set the ShowSelectLink
and ShowDeleteLink
property to true
. Once a row is selected it will raise the SelectedIndexChange
event. The same thing happens when the delete link is clicked; it raises the RowDelete
event. Both of these events pass the CommandName
and CommandArgument
but for this the DataKeyName
must to be set. For example if we set the DataKeyName
to the primary key of a table in these events it will have the primary key value as CommandArgument
. You can also select a row by using the SelectedIndex
property or the Select()
method. To deselect a row use the ResetSelection()
method.
The RowDataBound Event
In the RowDataBound
event we can do some special processing before the data is bound. For example when showing the Products
table of Northwind database we can change the background color to red
that Unit in Stock is less than 10. Another example could be that our Web Service returns the Product
's CategoryID
but we want to show the category name instead of that CategoryID
. These kinds of changes can be done in this event. This event passes the binding row and the current data item that it is binding. The following shows how to bind this event and do the special processing.
Code Listing 5: RowDataBound
- function pageLoad()
- {
- // Getting the reference of the Client Components
- // and attaching the event handlers
- _grid = $find('grid');
- _grid.add_rowDataBound(rowDataBound);
- }
- function rowDataBound(sender, e)
- {
- var product = e.get_dataItem();
- var tdCategory = e.get_tableRow().cells[2];
- var categoryName = getCategoryName(product.CategoryID);
- tdCategory.innerHTML = categoryName;
- var tdUnitsInStock = e.get_tableRow().cells[5];
- if (product.UnitsInStock < 10)
- {
- tdUnitsInStock.style.backgroundColor = '#ff0000';
- }
- }
Figure 4: RowDataBound
The Product.aspx of the attached sample has the full source code of the RowDataBound
event example.
Paging
When working with large tables we often required to use paging. Although the DataGrid/GridView
has built-in support for paging they are pretty much useless. Most developers often refuse to use the built-in functionality and use their own custom logic which usually takes a start index, page size and other additional parameters and in turn returns only the paged records with the total number of records. The sample DataService.asmx
contains some of the methods (GetCustomerList
, GetProductList
) which contain the custom paging logic. Usually a Pager
shows the page numbers, next/previous, first/last page links. The following shows how to implement a pager control.
Code Listing 6: AJAX Grid Pager JavaScript
- function pageLoad()
- {
- // Getting the reference of the Client Components
- // and attaching the event handlers
- _grid = $find('grid');
- _grid.add_sort(sorted);
- _pager = $find('pager');
- _pager.add_pageChange(pageChanged);
- //Getting the reference of the DOM elements
- _message = $get('message');
- loadCustomers();
- }
- function sorted(sender, e)
- {
- // Set the SortColum and SortOrder of the Grid so that
- // it can properly render current sort column
- // and the associated image
- _grid.set_sortColumn(e.get_sortColumn());
- _grid.set_sortOrder(e.get_sortOrder());
- // need to reset the current page as sorting has been changed
- _pager.set_currentPage(1);
- loadCustomers();
- }
- function pageChanged(sender, e)
- {
- // Set the new page as current page
- _pager.set_currentPage(e.get_newPage());
- loadCustomers();
- }
- function loadCustomers()
- {
- // Calculating the startindex
- var startIndex = ((_pager.get_currentPage()-1) * _pager.get_rowPerPage());
- // Need to convert the sortoder which our WS can understand
- // This needs to be on one line. Its been wrapped to display better in this article.
- var sortOrder = (_grid.get_sortOrder() == Ajax.Controls.GridSortOrder.Descending)
- ? 'DESC' : 'ASC';
- _message.innerHTML = "<div>";
- _message.innerHTML += "<img alt='' src='Images/indicator.gif' />";
- _message.innerHTML += "Loading Customers...</div>";
- _message.style.display = "";
- DataService.GetCustomerList
- (
- startIndex,
- _pager.get_rowPerPage(),
- _grid.get_sortColumn(),
- sortOrder,
- function(pagedResult)
- {
- var total = 0;
- var customers = null;
- if (pagedResult != null)
- {
- total = pagedResult.Total;
- customers = pagedResult.Rows;
- }
- _grid.set_dataSource(customers);
- _grid.dataBind();
- _pager.set_rowCount(total);
- _message.innerHTML = '';
- _message.style.display = 'none';
- },
- function(exception)
- {
- _message.innerHTML = '' + exception.get_message() + '';
- }
- );
- }
Code Listing 7: AJAX Grid Pager ASPX
- <form id="form1" runat="server">
- <asp:ScriptManager ID="TheScriptManager" runat="server">
- <Services>
- <asp:ServiceReference Path="~/DataService.asmx" />
- </Services>
- </asp:ScriptManager>
- <table border="0" cellpadding="1" cellspacing="0" style="width:100%">
- <tbody>
- <tr>
- <td style="text-align:left">
- <ajax:Grid ID="grid" runat="server"
- Border="0" CellPadding="5" CellSpacing="0" CssClass="grid"
- HeaderCssClass="gridHeader" RowCssClass="gridRow" AlternatingRowCssClass="gridAltRow"
- SelectedRowCssClass="gridSelectedRow" SortColumn="CompanyName"
- SortOrderAscendingImage="Images/up.gif" SortOrderDescendingImage="Images/dn.gif">
- <Columns>
- <ajax:GridColumn
- DataField="CompanyName"
- HeaderText="Company"
- Sortable="True" Nowrap="True"/>
- <ajax:GridColumn
- DataField="ContactTitle"
- HeaderText="Title" Sortable="True"/>
- <ajax:GridColumn
- DataField="ContactName"
- HeaderText="Contact"
- Sortable="True"/>
- <ajax:GridColumn
- DataField="Phone"
- HeaderText="Phone"
- Sortable="True"/>
- </Columns>
- </ajax:Grid>
- </td>
- </tr>
- <tr>
- <td style="text-align:right">
- <ajax:Pager ID="pager" runat="server" CssClass="pager"
- CurrentPageCssClass="pagerCurrentPage" OtherPageCssClass="pagerOtherPage"
- ShowInfo="True" InfoCssClass="pagerInfo"></ajax:Pager>
- </td>
- </tr>
- <tr>
- <td style="text-align:left"><div id="message" style="display:none"></div></td>
- </tr>
- </tbody>
- </table>
- </form>
Figure 5: AJAX Grid Pager
The followings are some of the important properties of the AJAX Pager
:
ShowInfo
: Whentrue
, shows the info such as Page 1 of 10. The default value isfalse
.ShowFirstAndLast
: Whentrue
, shows the first and last Link. The default value istrue
.FirstText
: The text which will be displayed as link for the first page. The Default value is <<LastText
: The text which will be displayed as link for the last page. The Default value is >>ShowPreviousAndNext
: Whentrue
, shows the Previous and Next Link. The default value isfalse
.ShowNumbers
: Whentrue
, shows the page numbers as link. The default value istrue
.RowPerPage
: The Number of row that each page contains. The default value is 10.CurrentPage
: The currentpage that the pager is showing.HideOnSinglePage
: The control will not be rendered if it founds there is only one page.ShowTip
: Whentrue
, a tooltip will appears on hovering on any of the links.InfoCssClass
: Styling property for the info part.CurrentPageCssClass
: Styling property for the current page.OtherPageCssClass
: Styling property for other pages.
The AJAX Pager
contains only one event PageChange
that the developers have to subscribe to load the new page data. I have excluded the Pager
from the Grid
so that it can be utilize in with other controls that show tabular data.
Both the Customer.aspx and Product.aspx of the attached sample has full source code of the Paging example.
Drag and Drop
Drag and Drop is an essential part of any Rich Web Application and thus it has become a common feature for Web 2.0 applications. Certianly Pageflakes is one of the best candidates for utlizing drag and drop. The Ajax Grid
has built-in support for column drag and drap. Just set the AllowDragAndDrop
property for any Column
to true
and it will be drag and dropable. The following screenshot shows the implemented version of a drag and drop in the Customers
table of the Northwind database:
Figure 5: AJAX Grid Drag and Drop
The Ajax Grid
raises the ColumnDragStarted
when the column drag started and ColumnDropped
upon dropping the column. The following code shows how to track the column and drag and drop in these events.
Code Listing 8: AJAX Grid Drag and Drop
- function pageLoad()
- {
- _grid = $find('grid');
- _grid.add_columnDragStart(columnDragStart);
- _grid.add_columnDropped(columnDropped);
- }
- function columnDragStart(sender, e)
- {
- alert(e.get_column().headerText); // the event passes the column reference
- }
- function columnDropped(sender, e)
- {
- // this event also passes the column reference with old and new index
- alert(e.get_column().headerText);
- alert(e.get_oldIndex());
- alert(e.get_newIndex());
- }
We can also use the built-in ProfileService
to persist the columns position, so that in the next visit the columns positioning is same as the user left it in the last visit.
Summary
Microsoft ASP.NET AJAX is great platform to develop web application but currently it is lacking of Client Side Components especially which works with data. Although you will find 30+ controls in ASP.NET Ajax ToolKit but most of them are mainly extender, which extends existing server side ASP.NET Controls. Certainly we can develop these kinds of controls to enrich it.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步