今天因为菜单的问题, 需要用到递归算法, 在此记录一下:
1.表结构如下:(这里只是展示两个比较重要的字段) ,大家应该都看明白
2.先定义一个菜单结构类.
3.实现递归.
private List<TreeChildViewModel> AddChildN(string Pid)
{
var data = _perssionRepsonsityService.GetAllList().Where(x => x.ParentID == Pid);//这里是获取数据
List<TreeChildViewModel> list = new List<TreeChildViewModel>();
foreach (var item in data)
{
//这一块主要是转换成TreeChidViewModel的值.
TreeChildViewModel childViewModel = new TreeChildViewModel();
childViewModel.id = item.ID;
childViewModel.component = item.Component;
childViewModel.name = item.Name;
childViewModel.meta_icon = item.Meta_icon;
childViewModel.meta_title = item.Meta_title;
childViewModel.meta_content = item.Meta_content;
childViewModel.treeChildren = GetChildList(childViewModel);
list.Add(childViewModel);
}
return list;
} public List<TreeChildViewModel> GetChildList(TreeChildViewModel treeChildView)
{
if (!_perssionRepsonsityService.IsExists(x => x.ParentID == treeChildView.id))
{
return null;
}
else
{
return AddChildN(treeChildView.id);
}
}
4.调用
public string Client()
{
List<TreeChildViewModel> treeViewModels = new List<TreeChildViewModel>(); treeViewModels= AddChildN("");
return JsonConvert.SerializeObject(treeViewModels);
}
5.结果展示
[
{
"id":"1",
"pathRouter":null,
"name":"用户管理",
"component":"123123",
"meta_title":null,
"meta_content":null,
"meta_icon":null,
"treeChildren":[
{
"id":"2",
"pathRouter":null,
"name":"table",
"component":"123123",
"meta_title":null,
"meta_content":null,
"meta_icon":null,
"treeChildren":[
{
"id":"5",
"pathRouter":null,
"name":"table",
"component":"123123",
"meta_title":null,
"meta_content":null,
"meta_icon":null,
"treeChildren":null
}
]
}
]
},
{
"id":"3",
"pathRouter":null,
"name":"table",
"component":"123123",
"meta_title":null,
"meta_content":null,
"meta_icon":null,
"treeChildren":[
{
"id":"4",
"pathRouter":null,
"name":"table",
"component":"123123",
"meta_title":null,
"meta_content":null,
"meta_icon":null,
"treeChildren":null
}
]
},
{
"id":"6",
"pathRouter":null,
"name":"table",
"component":"123123",
"meta_title":null,
"meta_content":null,
"meta_icon":null,
"treeChildren":null
}
]
6.这里是全部菜单获取的, 如果是根据角色来判断权限获取的话, 在AddChildN 的foreach 里面进行权限进行过滤, 如果该角色ID下的权限包含有相应的权限ID,则执行,否则,直接跳出循环. ,但是这最终还得根据实际表结构来进行过滤.
7.总结, 其实我这差不多是误打误撞写出来的,算做个记录吧..