Introduction
As web development moves towards pure client-side processing (HTML and JavaScript), it will be important to have a readily available set of reusable controls built entirely for the client. This article and associated code features a Grid control written this way. It supports the following functionality:
- Use JSON object as the data source
- Row selection
- Row identifier (i.e., data key name)
- Sorting by clicking on the column header (not applicable when grouping)
- Alternate row display
- Scroll bars
- Group/display by a given group field (see below)
Future potential enhancements:
- Paging
- Fixed-header when scrolling
Background
The ASP.NET GridView
control is a server-side control that this control is meant to replace. The GridView
has a number of missing features and developers end up customizing the server-side control only to find it's cumbersome due to the postback model (the custom code usually ends up being client-side code anyway).
Using the Code
The Grid control is wrapped in a JavaScript class and is quite easy to use. Currently, the only type of data source it supports is a JSON object (what else would you want anyway). This allows you, for example, to call a REST service and assign the returned data directly to the grid.
In your HTML, declare a <table>
element with an id (and, optionally, a CSS class for your own styling). This is where the grid will be displayed.
To use, first call the only constructor on the Grid
class like this:
var myGrid = new Grid('myGrid', testData);
Then set any (public
) properties on the created object depending on what functionality is desired. The only other required property is the bindFields
property. An example of how to set the bindFields
property is as follows:
myGrid.bindFields =[{ "FieldName": "make", "Header": "Make",
"Width": 150 },{ "FieldName": "model", "Header": "Model", "Width": 150 },
{ "FieldName": "year", "Header": "Year", "Width": 50 }];
See the comments inside the class for a description of all public
properties and methods.
Finally, call the Build public
method to generate the grid:
myGrid.Build();
See the documentation at the top of the grid.js file for a complete code example with test data. Also, a test HTML file along with a CSS file has been uploaded with the .js file as an example of how to use and style the control.
Points of Interest
No JavaScript frameworks, e.g., jQuery or Dojo, are used.
History
- Revision 1 - Fix for IE7, Chrome, and Firefox - 09/28/2012 - Uploaded new source code
- Revision 2 - Added download link (below)
- Revision 3 - Fix for better column alignment on grouping, new support for a expand/collapse image, and now including jquery file