EasyUI TreeGrid DataTable转换数据实现案例

时间:2021-06-11 07:57:29

C#部分

/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
int OneID = int.Parse(context.Request["ID"]);
string sql = "SELECT id, OneID, TreeID, Text, Cfj FROM MenuTree where OneID="+OneID+" order by TreeID,reorder,id "; DataTable dt = DbHelper.QueryDataTable(sql);
string json2 = TableToEasyUITreeJson(dt, "TreeID", "", "id", "Text").Substring();
context.Response.Write(json2.ToString());
} /// <summary>
/// 递归将DataTable转化为适合jquery easy ui 控件tree ,combotree 的 json
/// 该方法最后还要 将结果稍微处理下,将最前面的,"children" 字符去掉.
/// </summary>
/// <param name="dt">要转化的表</param>
/// <param name="pField">表中的父节点字段</param>
/// <param name="pValue">表中顶层节点的值,没有 可以输入为0</param>
/// <param name="kField">关键字字段名称</param>
/// <param name="TextField">要显示的文本 对应的字段</param>
/// <returns></returns>
public static string TableToEasyUITreeJson(DataTable dt, string pField, string pValue, string kField, string TextField)
{
StringBuilder sb = new StringBuilder();
string filter = string.Empty;
if (pValue.ToString() == "")
{
filter = string.Format("{0} is null", pField);
}
else
{
filter = string.Format("{0}='{1}'", pField, pValue);
}
DataRow[] drs = dt.Select(filter);
if (drs.Length < )
return "";
sb.Append(",\"children\":[");
foreach (DataRow dr in drs)
{
string pcv = dr[kField].ToString();
sb.Append("{");
sb.AppendFormat("\"id\":\"{0}\",", dr[kField].ToString());
sb.AppendFormat("\"text\":\"{0}\"", dr[TextField].ToString());
sb.Append(TableToEasyUITreeJson(dt, pField, pcv, kField, TextField).TrimEnd(','));
sb.Append("},");
}
if (sb.ToString().EndsWith(","))
{
sb.Remove(sb.Length - , );
}
sb.Append("]");
return sb.ToString(); }

html 部分

<able id="Table1" style="width:600px;height:400px"></table>
<script type="text/javascript">
var dd = '[{"id":"0001","text":"1","children":[{"id":"00010001","text":"4","children":[{"id":"000100010001","text":"7","children":[{"id":"0001000100010001","text":"9","children":[{"id":"00010001000100010001","text":"10","children":[{"id":"000100010001000100010001","text":"11","children":[{"id":"0001000100010001000100010001","text":"12"}]}]}]}]},{"id":"000100010002","text":"8"}]},{"id":"00010002","text":"5"},{"id":"00010003","text":"6"}]},{"id":"0002","text":"2"},{"id":"0003","text":"3"}]'; $(function(){
$('#Table1').treegrid({
url: '../Handler1.ashx?id=2', idField:'id',
treeField: 'text',
columns:[[
{ field: 'text', title: 'text', width: 200, align: 'left' },
]]
}); }) </script>