public object ListMenu(DataTable _list)
{
StringBuilder sb = new StringBuilder();
DataRow[] rows = _list.Select("PID=0");
sb.Append("[");
bool isFist = false;
foreach (DataRow dr in rows)
{
if (isFist)
sb.Append(",");
isFist = true;
string id = dr["ID"].ToString();
sb.Append("{");
sb.AppendFormat(""id":"{0}",", dr["ID"]);
sb.AppendFormat(""text":"{0}",", dr["Name"]);
sb.AppendFormat(""pid":"{0}",", dr["PID"]);
string submenu = GetSubMenu(id, _list);
if (submenu == "")
{
sb.AppendFormat(""leaf":"{0}",", "true");
sb.Append(""children":[");
}
else
{
sb.AppendFormat(""expanded":"{0}",", "true");
sb.Append(""children":[");
sb.Append(submenu);
}
sb.Append("]");
sb.Append("}");
}
sb.Append("]");
_menu = sb.ToString();
return _menu;
}
private string GetSubMenu(string pid, DataTable dt)
{
StringBuilder sb = new StringBuilder();
DataRow[] rows = dt.Select("PID=" + pid);
if (rows.Length > 0)
{
bool isFist = false;
foreach (DataRow dr in rows)
{
if (isFist)
sb.Append(",");
isFist = true;
string id = dr["ID"].ToString();
sb.Append("{");
sb.AppendFormat(""id":"{0}",", dr["ID"]);
sb.AppendFormat(""text":"{0}",", dr["Name"]);
sb.AppendFormat(""pid":"{0}",", dr["PID"]);
string submenu = GetSubMenu(id,dt);
if (submenu == "")
{
sb.AppendFormat(""leaf":"{0}",", "true");
sb.Append(""children":[");
}
else
{
sb.AppendFormat(""expanded":"{0}",", "true");
sb.Append(""children":[");
sb.Append(submenu);
}
sb.Append("]");
sb.Append("}");
}
}
return sb.ToString();
}
可根据实际情况修改相应的值:如children可能是nodes