新项目开始,打算通过c# + jquery easy ui 设计一个通用的目录树加载模块。具体实现如下:
后台代码:
/// <summary>
/// 返回Json格式的UILI string类型结构
/// </summary>
private void GetMenu()
{
int UserID = 0;
int.TryParse(System.Web.HttpUtility.UrlDecode(Request["UserID"]), out UserID);
if (UserID > 0)
{
//根据UserID获取 module列表 //这里定义是两重
IList<Model.PM_Module> m_M_PM = new List<Model.PM_Module>();
m_M_PM = m_B_PM.GetMenuByUserID(UserID);
TreeNode root = new TreeNode("root", "root");
//初定设置为两个层级
foreach (Model.PM_Module item in m_M_PM)
{
if (item.ParentModuleID == 0)
{
TreeNode pNode = new TreeNode(item.ModuleID.ToString(), item.ModuleName,"",item.URL,"");
foreach (Model.PM_Module cItem in m_M_PM)
{
if (cItem.ParentModuleID == item.ModuleID)
{
TreeNode cNode = new TreeNode(cItem.ModuleID.ToString(), cItem.ModuleName, "", cItem.URL, "");
pNode.ChildNodes.Add(cNode);
}
}
root.ChildNodes.Add(pNode);
}
}
//将树生成json字符串
returnValue = CreateMenu(root);
}
else
{
returnValue = "";
}
}
private string CreateMenu(TreeNode tree)
{
string strResult = "[";
foreach (TreeNode child in tree.ChildNodes)
{
string strItem = "\"id\":\"{0}\",\"text\":\"{1}\",\"children\":{2},\"url\":\"{3}\",\"parenttext\":\"{4}\"";
string strId = child.Text.ToString();
string strUrl = child.NavigateUrl.ToString();//Lib.EncodeUrlParas(row["url"].ToString());
string strMenuName = child.Value;
string strMotion = "\"Regeditsrc('" + child.NavigateUrl + "','" + child.Parent.Value + "->" + child.Value + "')\"";
string strParentText = "";
if (child.Parent.Value != "root")
{
strParentText = child.Parent.Value + "->" + child.Value;
}
string strChild = "[]";
if (child.ChildNodes.Count>0)
{
strChild = CreateMenu(child);
}
strItem = string.Format(strItem, new string[] { strId, strMenuName, strChild,strUrl, strParentText });
strResult += "{" + strItem + "}";
strResult += ",";
}
if (strResult.EndsWith(","))
{
strResult = strResult.Substring(0, strResult.Length - 1);
}
strResult += "]";
return strResult ;
}
前台js:
<script type="text/javascript">
$(document).ready(function () {
loadMenuJson();
});
function loadMenuJson() {
$.ajax({
url: "CommonHelpers/Menu/GetJsonUiLiMenu.aspx",
dataType: "html",
data: {
UserID: 1
},
success: function (returnValue) {
if ($.trim(returnValue).length > 0) {
$('#Menu').tree({
data: eval(returnValue),
onClick: function (node) {
if (node.parenttext != "") {
Regeditsrc(node.url, node.parenttext);
}
}
});
}
else {
}
}
});
}
</script>
<script type="text/javascript">
function Regeditsrc(src, center) {
document.getElementById("mainFram").src = src;
$('#bodydiv').layout('panel', 'center').panel({ title: center });
}
</script>
前台html:
<ul id="Menu" class="easyui-tree" style="width: 100%; padding: 0 0 0 0; margin: 0 0 0 0;"
data-options="fit:true,dnd:false">