jqGrid supports tree-grid mode, where you can display rows of data of the same structure (column definition)
as hierarchial tree structure. In your model, just set the
TreeGridSettings.Enabled property to true
and the grid will be assuming tree-mode response from the server (see the
Model code tab for details).
This means that in addition to the row data, you need to return data that will help jqGrid determine the hierarchy of the rows.
When selecting rows, you need to specify some or all of the following reserved fields
- tree_level - the level of the row in the tree hierarchy. 0 is for root row.
- tree_leaf - if the row is leaf (no child rows). This will make it non-expandable and will have an alternative icon.
- tree_expanded - if the row is expanded by default or not.
- tree_parent - the primary key (ID) of the parent row (only applicable for child rows)
- tree_loaded - true/false - if the tree nodes are already loaded. Can be used to show several levels expanded by default.
You can also control the different images per grid rows - in expanded, collapsed and leaf states. This can be achieved with the following properties available from the
TreeGridSettings collection -
ExpandedIcon,
CollapsedIcon,
LeafIcon
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Trirand.Web.Mvc;
using System.Web.UI.WebControls;
namespace JQGridMVCExamples.Models
{
public class FileJqGridModel
{
public JQGrid FileDataGrid { get; set; }
public FileJqGridModel()
{
FileDataGrid = new JQGrid
{
Columns = new List()
{
new JQGridColumn {
DataField = "ID",
PrimaryKey = true,
Visible = false,
Sortable = false
},
new JQGridColumn {
DataField = "Name",
Width = 350,
Sortable = false
},
new JQGridColumn {
DataField = "Size",
Width = 100,
Sortable = false
},
new JQGridColumn {
DataField = "DateCreated",
HeaderText = "Date Created",
Width = 100,
Sortable = false
},
new JQGridColumn {
DataField = "LastModified",
HeaderText = "Last Modified",
Width = 100,
Sortable = false
},
},
Width = Unit.Pixel(650),
Height = Unit.Percentage(350),
TreeGridSettings = new TreeGridSettings
{
Enabled = true
}
};
}
}
}
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<JQGridMVCExamples.Models.FileJqGridModel>" %>
<%@ Import Namespace="Trirand.Web.Mvc" %>
<%@ Import Namespace="JQGridMVCExamples.Models" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>jqGrid TreeGrid - Browse Files</title>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="http://www.trirand.net/aspnetmvc/Scripts/trirand/i18n/grid.locale-en.js"></script>
<script type="text/javascript" src="http://www.trirand.net/aspnetmvc/Scripts/trirand/jquery.jqGrid.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/themes/redmond/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="http://www.trirand.net/aspnetmvc/Content/themes/ui.jqgrid.css" />
</head>
<body>
<div>
<%= Html.Trirand().JQGrid(Model.FileDataGrid, "FileBrowserGrid") %>
</div>
<br /><br />
<div>
<% Html.RenderPartial("CodeTabs"); %>
</div>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using JQGridMVCExamples.Models;
using System.Web.UI.WebControls;
using Trirand.Web.Mvc;
using System.IO;
using System.Collections;
namespace JQGridMVCExamples.Controllers.Grid
{
public partial class GridController : Controller
{
// Create a view model that unifies both Directories and Files
public class DirectoryEntry
{
public string ID { get; set; }
public bool IsDir { get; set; }
public string Name { get; set; }
public string Size { get; set; }
public string DateCreated { get; set; }
public string LastModified { get; set; }
public bool tree_expanded { get; set; }
public bool tree_leaf { get; set; }
public int tree_level { get; set; }
public string tree_parent { get; set; }
}
// This is the default action for the View. Use it to setup your grid Model.
public ActionResult TreeFileBrowser()
{
// Get the model (setup) of the grid defined in the /Models folder.
var gridModel = new FileJqGridModel();
var grid = gridModel.FileDataGrid;
// Setting the DataUrl to an action (method) in the controller is required.
// This action will return the data needed by the grid
grid.DataUrl = Url.Action("TreeFileBrowser_DataRequested");
// set up the grid. make sure you call this in both the init controller (this controller)
// and in the DataRequested controller specified by DataUrl
FileBrowserGrid_SetUpGrid(grid);
// Pass the custmomized grid model to the View
return View(gridModel);
}
private void FileBrowserGrid_SetUpGrid(JQGrid grid)
{
// set grid tree mode to on. you can also set this in the Model.
grid.TreeGridSettings.Enabled = true;
// do not auto-sort by primary key - we have custom sorting - folders first, then files
grid.SortSettings.AutoSortByPrimaryKey = false;
// set the icons for lead, expanded and collapsed row. These are actually
// available styles in jQuery UI ThemeRoller themes
grid.TreeGridSettings.ExpandedIcon = "ui-icon-folder-open";
grid.TreeGridSettings.CollapsedIcon = "ui-icon-folder-collapsed";
grid.TreeGridSettings.LeafIcon = "ui-icon-document";
}
// This method is called when the grid requests data. You can choose any method to call
// by setting the JQGrid.DataUrl property
public JsonResult TreeFileBrowser_DataRequested()
{
// Get both the grid Model and the data Model
// The data model in our case is an autogenerated linq2sql database based on Northwind.
var gridModel = new FileJqGridModel();
var grid = gridModel.FileDataGrid;
FileBrowserGrid_SetUpGrid(grid);
string startingPath = HttpContext.Request.MapPath("~/");
JQGridTreeExpandData expandData = grid.GetTreeExpandData();
if (expandData.ParentID != null)
// GetDirectoryFrom hash returns the full path of the folder per its key (in the ID field of the row)
startingPath = GetDirectoryFromHash(expandData.ParentID);
// Take a snapshot of the file system.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(startingPath);
IEnumerable dirList = dir.GetDirectories("*.*",
System.IO.SearchOption.TopDirectoryOnly);
IEnumerable fileList = dir.GetFiles("*.*",
System.IO.SearchOption.TopDirectoryOnly);
// ********************************************************************************************
// when selecting rows, you need to specify some or all of the following reserved fields
// tree_level - the level of the row in the tree hierarchy. 0 is for root row.
// tree_leaf - if the row is leaf (no child rows). This will make it non-expandable and will have an alternative icon
// tree_expanded - if the row is expanded by default or not
// tree_parent - the primary key (ID) of the parent row (only applicable for child rows)
// tree_loaded - true/false - if the tree nodes are already loaded. Can be used to show several levels expanded by default.
// ********************************************************************************************
var dirs = from directory in dirList
orderby directory.Name
select new DirectoryEntry
{
// Use Hashtable to make sure there is unique key per folder fullname
ID = AddDirectoryToHash(directory.FullName),
IsDir = true,
Name = "" + directory.Name + "",
Size = "[dir]",
DateCreated = directory.CreationTime.ToString("d"),
LastModified = directory.LastWriteTime.ToString("d"),
tree_parent = expandData.ParentID,
tree_expanded = false,
tree_leaf = false,
tree_level = expandData.ParentLevel + 1
};
var files = from file in fileList
orderby file.Name
select new DirectoryEntry
{
// ID is the primary key and must be set to an unique key
// GUIDs can be used without the "-" - not allowed for IDs in HTML
ID = Guid.NewGuid().ToString().Replace("-", ""),
IsDir = false,
Name = file.Name,
Size = file.Length.ToString(),
DateCreated = file.CreationTime.ToString("d"),
LastModified = file.LastWriteTime.ToString("d"),
tree_parent = expandData.ParentID,
tree_leaf = true,
tree_level = expandData.ParentLevel + 1
};
var allFilesAndFolders = files.Concat(dirs)
.AsQueryable()
.OrderBy(f => f.Name)
.OrderBy(f => f.IsDir == false);
return grid.DataBind(allFilesAndFolders);
}
private string AddDirectoryToHash(string fullName)
{
Hashtable directoryHash = new Hashtable();
if (HttpContext.Session["directoryHash"] != null)
directoryHash = HttpContext.Session["directoryHash"] as Hashtable;
string key = directoryHash.Count.ToString();
directoryHash.Add(key, fullName);
HttpContext.Session["directoryHash"] = directoryHash;
return key;
}
private string GetDirectoryFromHash(string key)
{
Hashtable directoryHash = new Hashtable();
if (HttpContext.Session["directoryHash"] != null)
directoryHash = HttpContext.Session["directoryHash"] as Hashtable;
return directoryHash[key] as string;
}
}
}
Switch theme:
Theming is based on the very popular jQuery
ThemeRoller standard. This is the same theming mechanism used by jQuery UI and is now a de-facto standard for jQuery based components.
The benefits of using ThemeRoller are huge. We can offer a big set of ready to use themes created by professional designers, including Windows-like themes (Redmond), Apple-like theme (Cupertino), etc.
In addition to that any jQuery UI controls on the same page will pick the same theme.
Last, but not least, you can always roll your own ThemeRoller theme, using the superb
Theme Editor
To use a theme, simply reference 2 Css files in your Html <head> section - the ThemeRoller theme you wish to use, and the jqGrid own ThemeRoller Css file. For example (Redmond theme):
<link rel="stylesheet" type="text/css" media="screen" href="/themes/redmond/jquery-ui-1.8.2.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="/themes/ui.jqgrid.css" />