您的要求是在 启动带树视图
中显示用户详细信息这里我通过SQL数据库中的linq查询获取用户数据
这是样本JSON数据以这种方式如何在C#中准备数据
注意:引导树视图仅适用于那些键名称应与数据文本和节点中提到的相同,但在我的c#类中我有不同的字段名称,如下面的屏幕截图所示
示例JSON数据 - >如何在C#
中准备这样的数据var treeData = [{
text: "UserName 1", nodes: [ {
text: "First Name1"
},
{
text: "Last Name1"
},
{
text: "User Orders 1",
nodes: [
{
text: "Order 1"
},
{
text: "Order 2"
}
]
},
{
text: "User Locations 1",
nodes: [
{
text: "Location 1"
},
{
text: "Location 2"
}
]
}
]
},
{
text: "UserName 2", nodes: [{
text: "First Name 2"
},
{
text: "Last Name 2"
},
{
text: "User Orders 2",
nodes: [
{
text: "Order 1"
},
{
text: "Order 2"
}
]
},
{
text: "User Locations 2",
nodes: [
{
text: "Location 1"
},
{
text: "Location 2"
}
]
}
]
}
];
答案 0 :(得分:1)
首先,创建一个用作树视图节点的类:
[Serializable]
public class TreeviewNodeEntity
{
public string text { get; set; }
public string[] tags { get; set; }
public TreeviewNodeEntity[] nodes { get; set; }
}
其次,在控制器中创建一个动作,在该控制器中创建树视图的节点数据集。将此作为Json数据返回。请注意,要返回的根对象(returnObject)是一个节点对象数组。在tags属性(字符串数组类型)中,您可以存储id值或其他数据。
[HttpPost]
public ActionResult GetTreeData(int mainItem)
{
TreeviewNodeEntity[] returnObject = new TreeviewNodeEntity[2];
TreeviewNodeEntity rootNode1 = new TreeviewNodeEntity();
rootNode1.text = "Username 1";
rootNode1.tags = new string[1];
rootNode1.tags[0] = "1";
returnObject[0] = rootNode1;
rootNode1.nodes = new TreeviewNodeEntity[2];
TreeviewNodeEntity childNode = new TreeviewNodeEntity();
childNode.text = "First name1";
childNode.tags = new string[1];
childNode.tags[0] = "11";
rootNode1.nodes[0] = childNode;
childNode = new TreeviewNodeEntity();
childNode.text = "Last name1";
childNode.tags = new string[1];
childNode.tags[0] = "12";
rootNode1.nodes[1] = childNode;
TreeviewNodeEntity rootNode2 = new TreeviewNodeEntity();
rootNode2.text = "Username 2";
rootNode2.tags = new string[1];
rootNode2.tags[0] = "2";
returnObject[1] = rootNode2;
return Json(returnObject);
}
最后,打开必须显示树视图的视图并添加此Javascript代码。它使用Jquery,因此请确保在项目中安装它。
function BuildTree() {
$.ajax({
type: 'POST',
url: "/NameOfController/GetTreeData",
async: false,
data: "{'mainItem':'2'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
if (data) {
$('#tree').treeview({
data: data,
enableLinks: true,
showBorder: false,
onNodeSelected: function (event, data) {
if (data.tags instanceof Array) {
DoStuffWhenClickingOnNode(data.tags[0]);
}
}
});
}
},
error: function (error) {
alert(error.responseText);
}
});
}
不要忘记Html中的树元素:
<div id="tree"></div>
答案 1 :(得分:0)
在类
中添加声明上方的名称 [DataContract(Name = "MyName")]
internal class Person
{
[DataMember(Name = "xName")]
internal string name;
[DataMember(Name = "Age in Years")]
internal int age;
}