[英]Use jqTree with ASP MVC and JSON File
我剛剛將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);
}
您可以通過以下方式從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>
}
在HomeController
創建一個Nodes()
函數,如下所示:
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);
}
您將能夠查看您的樹。 如果您遇到任何問題,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.