c#部门普通List集合数据 转换成jqgrid treetable 数据格式 详细实现步骤
时间: 2024-03-05 18:51:07 浏览: 84
table表格样式利用jqgrid实现
3星 · 编辑精心推荐
要将 C# 部门普通 List 集合数据转换成 jqGrid treetable 数据格式,可以按照以下步骤进行实现:
1. 创建一个部门实体类,包含部门编号、部门名称、父级部门编号等属性。
2. 将部门数据存储在一个 List 集合中。
3. 将 List 集合中的数据转换成 JSON 格式。
4. 使用 JavaScript 将 JSON 格式的数据转换成 jqGrid treetable 数据格式。
下面是详细的实现步骤:
1. 创建部门实体类
```
public class Department
{
public int DepartmentId { get; set; } // 部门编号
public string DepartmentName { get; set; } // 部门名称
public int? ParentDepartmentId { get; set; } // 父级部门编号
}
```
2. 将部门数据存储在 List 集合中
```
List<Department> departmentList = new List<Department>();
departmentList.Add(new Department() { DepartmentId = 1, DepartmentName = "总公司", ParentDepartmentId = null });
departmentList.Add(new Department() { DepartmentId = 2, DepartmentName = "财务部", ParentDepartmentId = 1 });
departmentList.Add(new Department() { DepartmentId = 3, DepartmentName = "市场部", ParentDepartmentId = 1 });
departmentList.Add(new Department() { DepartmentId = 4, DepartmentName = "人事部", ParentDepartmentId = 1 });
departmentList.Add(new Department() { DepartmentId = 5, DepartmentName = "财务一部", ParentDepartmentId = 2 });
departmentList.Add(new Department() { DepartmentId = 6, DepartmentName = "财务二部", ParentDepartmentId = 2 });
departmentList.Add(new Department() { DepartmentId = 7, DepartmentName = "市场一部", ParentDepartmentId = 3 });
departmentList.Add(new Department() { DepartmentId = 8, DepartmentName = "市场二部", ParentDepartmentId = 3 });
departmentList.Add(new Department() { DepartmentId = 9, DepartmentName = "人事一部", ParentDepartmentId = 4 });
departmentList.Add(new Department() { DepartmentId = 10, DepartmentName = "人事二部", ParentDepartmentId = 4 });
```
3. 将 List 集合中的数据转换成 JSON 格式
```
var json = JsonConvert.SerializeObject(departmentList);
```
4. 使用 JavaScript 将 JSON 格式的数据转换成 jqGrid treetable 数据格式
```
var jsonData = JSON.parse(json);
var treeData = [];
var map = {};
for (var i = 0; i < jsonData.length; i++) {
var obj = jsonData[i];
map[obj.DepartmentId] = obj;
obj.children = [];
}
for (var i = 0; i < jsonData.length; i++) {
var obj = jsonData[i];
if (obj.ParentDepartmentId != null) {
map[obj.ParentDepartmentId].children.push(obj);
} else {
treeData.push(obj);
}
}
```
最终得到的 treeData 数组即为 jqGrid treetable 数据格式的数据。
阅读全文