87,914
社区成员
发帖
与我相关
我的任务
分享
public string getMenuJSON() //动态生成菜单JSON
{
string strSql;
string UserID = Session["UserID"].ToString();
strSql = "select * from tb_MenuParent where MPID in (select MPID from tb_MenuChild where MCID in(select MCID from tb_MenuUser where UserID='" + UserID + "')) order by MPID";
DataTable dtMenuParent = dbObj.GetDataSetStr(strSql, "dtMenuParent");
string strSqlC;
string strJson;
strJson = Convert.ToString("["); //JSON头
for (int i = 0; i < dtMenuParent.Rows.Count; i++)
{
strJson += "{'name': '" + dtMenuParent.Rows[i][1].ToString() + "','children': ["; //JSON父节点头
strSqlC = "select MCID,MCName,MCUrl from tb_MenuChild where MCID in(select MCID from tb_MenuUser where UserID='" + UserID + "') and MPID='" + dtMenuParent.Rows[i][0].ToString() + "' order by MCID";
DataTable dtMenuChild = dbObj.GetDataSetStr(strSqlC, "dtMenuChild");
for (int j = 0; j < dtMenuChild.Rows.Count; j++)
{
strJson += "{'Cname': '" + dtMenuChild.Rows[j][1].ToString() + "',"; //JSON子节点名称
strJson += "'Url':'" + dtMenuChild.Rows[j][2].ToString() + "'},"; //JSON子节点Url
}
strJson = strJson.Substring(0, strJson.Length - 1); //去除多余","
strJson += "]},"; //JSON父节点尾
dtMenuChild.Dispose();
}
strJson = strJson.Substring(0, strJson.Length - 1);
strJson += "]"; //JSON尾
dtMenuParent.Dispose();
return strJson;
}
这个代码是我亲测有效的代码,有些自定义类和方法,跟书上教程的命名方式是一样的,应该能看懂,我就懒得去改成通用的代码了,希望能帮到你。