我有这样定义的 Category 对象:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int ParentCategoryId { get; set; }
}
然后我虚构地创建如下数据:
public ICollection<Category> GetCategories()
{
List<Category> lst = new List<Category>();
//Top
lst.Add(new Category { Id = 1, Name = "Car", Description = "Car", ParentCategoryId = 0 });
lst.Add(new Category { Id = 2, Name = "Boats", Description = "Boats", ParentCategoryId = 0 });
//Catalogs
lst.Add(new Category { Id = 3, Name = "Winter2012", Description = "Parts & Accessories", ParentCategoryId = 1 });
lst.Add(new Category { Id = 4, Name = "Gear2012", Description = "Gear", ParentCategoryId = 1 });
//Categories
lst.Add(new Category { Id = 5, Name = "NewItems", Description = "New Stuff", ParentCategoryId = 3 });
lst.Add(new Category { Id = 6, Name = "Promo1", Description = "Promo1", ParentCategoryId = 3 });
lst.Add(new Category { Id = 7, Name = "Promo2", Description = "Promo2", ParentCategoryId = 3 });
//Sub-Categories (if any)
lst.Add(new Category { Id = 8, Name = "Men", Description = "Men", ParentCategoryId = 5 });
lst.Add(new Category { Id = 9, Name = "Women", Description = "Women", ParentCategoryId = 5 });
lst.Add(new Category { Id = 10, Name = "Kids", Description = "Kids", ParentCategoryId = 5 });
return lst;
}
我正在尝试构建一个复选框 TreeView,目前正在查看 jsTree 插件。最后,树视图看起来有点像:Top-->Catalogs-->Categories-->Sub-Categories
在我的 Controller 中,我填充了一个 ViewModel (HomeModel),然后调用 View。
public ActionResult Index()
{
Data.Data d = new Data.Data();
var customerGroups = d.GetCustomerGroups();
var model = new HomeModel();
model.CategoryStructure = d.GetCategories();
return View(model);
}
HomeModel 的定义如下:
public class HomeModel
{
//The checkbox hierarchy structure.
public IEnumerable<Category> CategoryStructure { get; set; }
//The selected category Id's once submitted.
public IEnumerable<int> CategorySelectList { get; set; }
}
当然,View 是 HomeModel 的强类型,看起来有点像这样:
…some html…
<div id="tree">
<ul id="treeview">
@CategoryTree(Model.CategoryStructure, 0)
</ul>
</div>
…some html…
@helper CategoryTree(IEnumerable<Category> nodes, int? parentId)
{
if (nodes.Any(n => n.ParentCategoryId == parentId))
{
<ul>
@foreach (var node in nodes.Where(n => n.ParentCategoryId == parentId))
{
<li>
<input type="checkbox" name="CategorySelectList" id="@node.Id" value="@node.Id" /> <label for="@node.Id">@node.Description</label>
@CategoryTree(nodes, node.Id)
</li>
}
</ul>
}
}
一切都很好!我有这个<ul>’s and <li>’s
格式精美的漂亮列表。设置所有必要的 jsTree 文件后,我执行以下操作:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
$("#treeview").jstree();
});
//]]>
</script>
jsTree 插件似乎很好地适用于我手动构建的树视图,但基本的“单击父节点不会检查/选择所有子节点”。
我怎样才能做到这一点?
提前致谢!