ztree的数据绑定
首先应用JS文件和样式文件
<script src="../JavaScript/ZTree/jquery-ztree-2.2.min.js" type="text/javascript"></script>
<link href="../JavaScript/ZTree/zTreeStyle/zTreeIcons.css" rel="stylesheet" type="text/css" />
<link href="../JavaScript/ZTree/zTreeStyle/zTreeStyle.css" rel="stylesheet" type="text/css" />
其次:json值绑定
var treeData;
$.ajax({
type: "Get", //请求的方法
url: '',//要传递参数使用Ajax进行处理的类名称
dataType: "text", //返回的数据类型
global: false, //Ajax的范围
async: false, //异步执行
//成功情况下的处理
success: function (strReult) {
treeData=eval(strReult);
}, //失败情况下的处理
error: function () {
alert("Ajax请求数据失败!");
}
});
var setting = {
showLine: true,
checkable: false,
};
zTree = $("#ulUserTree").zTree(setting, treeData);
后台处理json处理;数据库中查出的数据集放在DataTable 中传入如下方法返回json数据
//json处理
#region
/// <summary>
/// 表格数据生成指定格式的json数据
/// </summary>
/// <param name="dt">生成json数据的报表</param>
/// <returns></returns>
public static string DtToJson(DataTable dt)
{
string result = string.Empty;
foreach (DataRow dr in dt.Select("parentid=0"))
{
result += "," + AppendJson(dr, dt);
}
if (result.Length > 0)
result = "[\r\n" + result.Substring(1) + "\r\n]";
return result;
}
/// <summary>
/// 生成指定的Json数据
/// </summary>
/// <param name="dr">报表行对象</param>
/// <param name="dtAll">报表对象</param>
/// <returns></returns>
private static string AppendJson(DataRow dr, DataTable dtAll)
{
string parentNode = string.Empty;
string isTrue = "false";
DataRow[] rows = dtAll.Select("parentid='" + dr["VALUE"].ToString().Trim() + "'");
if (rows.Length == 0)
{
parentNode = "\r\n{name:{name},icon:\"{icon}\",open:" + isTrue + ", checked:false, id:\"{id}\"" + "\r\n}";
parentNode = parentNode.Replace("{name}", dr["name"].ToString())
.Replace("{id}", dr["VALUE"].ToString()).Replace("{icon}", dr["icon"].ToString());
}
else
{
string result = string.Empty;
foreach (DataRow row in rows)
{
result += "," + AppendJson(row, dtAll);
}
if (result.Length > 0)
result = "[\r\n" + result.Substring(1) + "\r\n]";
parentNode = "\r\n{name:{name},icon:\"{icon}\",open:" + isTrue + ", checked:false, id:\"{id}\",nodes:" + result + "\r\n}";
parentNode = parentNode.Replace("{name}", dr["name"].ToString())
.Replace("{id}", dr["VALUE"].ToString()).Replace("{icon}", dr["icon"].ToString());
}
return parentNode;
}
#endregion