首先数据为自包含结构1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25class Category
{
public int Id { get; set; }
public string Name { get; set; }
public int Father { get; set; }
private Category parentCategory;
public Category ParentCategory {
get
{
return Father!=0 ? new Category(new DictCategoryServer\(\).GetById(Father)) : null;
}
set { parentCategory = value; }
}
public Category(DictCategory dict)
{
this.Id = dict.Id;
Name = dict.Name;
Father = dict.FatherCategory;
}
}
其用到的数据库实体类为:1
2
3
4
5
6
7
8
9
10
11public class DictCategory
{
public int Id { get; set; }
public string Name { get; set; }
public string Note { get; set; }
public int FatherCategory { get; set; }
}
这样在对应的控制器里可以直接返回想要的结果1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23public ActionResult GetDictionaryItem(int id)
{
Category category = new Category(new DictCategoryServer\(\).GetById(id));
return Json(new
{
Result = new Result\(\){Success = true,Note = ""},
DictionaryItem = new
{
id = result.Id,
name = result.Name,
thumbnailUrl = result.ThumbnailUrl,
unitPrice = result.Price,
measurementUnits = result.MeasurementUnit,
category = new
{
id = category.Id,
name = category.Name,
parentCategory = category.ParentCategory
}
}
});
最终的结果就是能够给前台递归直到father为0的 DictCategory