我刚刚将jqTree添加到我的ASP MVC应用程序中。我需要在我的视图中显示TreeView:
@{
ViewBag.Title = "Tree";
}
<h2>@ViewBag.Title</h2>
<div id="tree1" data-url="/Home/Nodes"></div>
@section scripts {
<script language="javascript" type="text/javascript">
$(function () {
$('#tree1').tree();
});
</script>
}
我的数据在JSON文件中(〜/ App_Data / Roles.json):
{
"id": 1,
"label": "Role1",
"children": [
{
"id": 2,
"label": "Role2",
"children": [
{
"id": 3,
"label": "Role3",
"children": [
]
},
{
"id": 4,
"label": "Role4",
"children": [
]
}
]
}
]
}
如何在控制器操作方法中加载json文件以在视图中显示相应的TreeView?
public ActionResult Nodes()
{
var roles = // load json file
return Json(roles, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:1)
您可以从JSON文件(〜/ App_Data / Roles.json)传递json,并按以下方式创建树:
在视图中添加以下代码:
<div id="tree1"></div>
@section scripts {
<script language="javascript" type="text/javascript">
$.ajax({
type: 'POST', // we are sending data so this is POST
traditional: true,
url: '/Home/Nodes', // controller/action name
success: function (d) {
$('#tree1').tree({
data: [jQuery.parseJSON(d)]
});
}
});
</script>
}
在Nodes()
中创建HomeController
功能:
public ActionResult Nodes()
{
string roles = string.Empty;
using (StreamReader r = new StreamReader(Server.MapPath("~/App_Data/Roles.json")))
{
roles = r.ReadToEnd();
}
return Json(roles, JsonRequestBehavior.AllowGet);
}
您将能够查看您的树。如果您遇到任何问题,请告诉我。