【发布时间】:2015-09-14 09:49:37
【问题描述】:
我正在使用Bootstrap-Treeview .我想从服务器获取如下格式的json数据。
$("#tree").treeview({
data: getTree(),
levels: 6
});
function getTree() {
var tree = [{
text: "ED",
icon: "glyphicon glyphicon-user",
nodes: [{
text: "CPD",
icon: "glyphicon glyphicon-user",
nodes: [{
text: "Center Manager",
icon: "glyphicon glyphicon-user",
nodes: [{
text: "Manager",
icon: "glyphicon glyphicon-user",
nodes: [{
text: "Tech Head",
icon: "glyphicon glyphicon-user",
nodes: [{
text: "Individual",
icon: "glyphicon glyphicon-user",
}]
}]
}]
}]
}]
}];
var jsonTree = JSON.stringify(tree);
return jsonTree;
};
控制器动作方法如下
public ActionResult getJsonTree()
{
List<Role> _lstRole = _db.Roles.ToList();
List<RoleVM> _lstViewRole = new List<RoleVM>();
foreach(var _role in _lstRole)
{
if (_role.ChildID == null)
{
_lstViewRole=_db.Roles.Where(x=>x.Id==_role.Id).
Select(x=>new RoleVM(){
text=x.RoleName,
icon="glyphicon glyphicon-user"
}).ToList();
}
getChildNode(_role.Id, _lstViewRole);
}
var roles = _lstViewRole.ToArray();
return Json(roles, JsonRequestBehavior.AllowGet);
}
private void getChildNode(int _roleId, List<RoleVM> _lstRole)
{
RoleVM _childNode = _db.Roles.Where(x => x.ChildID == _roleId).
Select(x => new RoleVM()
{
text = x.RoleName,
icon = "glyphicon glyphicon-user"
}).FirstOrDefault();
_lstRole.Add(_childNode);
}
我得到的json格式如下
[
{
"text": "ED",
"icon": "glyphicon glyphicon-user",
"node": null
}, {
"text": "CPD",
"icon": "glyphicon glyphicon-user",
"node": null
}, {
"text": "Centre Manager",
"icon": "glyphicon glyphicon-user",
"node": null
}, {
"text": "Manager",
"icon": "glyphicon glyphicon-user",
"node": null
}, {
"text": "Tech Head",
"icon": "glyphicon glyphicon-user",
"node": null
},
{
"text": "Individual",
"icon": "glyphicon glyphicon-user",
"node": null
},
null
]
如何以正确的方式获取 json 格式。任何想法将不胜感激。
【问题讨论】:
标签: json twitter-bootstrap asp.net-mvc-4 treeview