填充子节点列表:Linq 混淆和关注点分离
我正在尝试在我的应用程序中实现树视图。我正在使用 MVC2 Preview 1 和 SubSonic 3 SimpleRepository。我对 MVC 和 Linq 都是新手。
我的问题是,我不确定如何将子节点列表添加到我传递回视图的模型记录中。因此,我在我的模型类中添加了一个名为 Children 的 IEnumerable,我将其填充到控制器操作中:
public class Category
{
public Category()
{
}
public int ID { get; set; }
public int? ParentId { get; set; }
[Required(ErrorMessage="Name is required")]
public string Name { get; set; }
[SubSonicIgnore]
public IEnumerable<Category> Children { get; set; }
}
然后在控制器操作中,我提取所有记录并迭代更新 Children 成员:
public ActionResult Index()
{
var categories = _repo.All<Category>();
foreach (var c in categories)
{
c.Children = from p in _repo.All<Category>()
where p.ParentId == c.ID
orderby p.Name
select p;
}
return View(categories);
}
我的 2 个问题是 #1 为什么这不是工作?在循环范围之外,我的更改将丢失。 #2 从一般意义上来说,这是正确的方法吗?将此代码放入控制器感觉就像黑客。
I am trying to implement a tree view in my application. I am using MVC2 Preview 1, and SubSonic 3 SimpleRepository. I am new to both MVC and Linq.
My problem is that I am not sure how to add a list of child nodes to the model record that I am passing back to the View. So I have added a IEnumerable called Children to my model class that I populate in the controller action:
public class Category
{
public Category()
{
}
public int ID { get; set; }
public int? ParentId { get; set; }
[Required(ErrorMessage="Name is required")]
public string Name { get; set; }
[SubSonicIgnore]
public IEnumerable<Category> Children { get; set; }
}
Then in the controller action, I pull all of the records and iterate through updating the Children member:
public ActionResult Index()
{
var categories = _repo.All<Category>();
foreach (var c in categories)
{
c.Children = from p in _repo.All<Category>()
where p.ParentId == c.ID
orderby p.Name
select p;
}
return View(categories);
}
My 2 questions are #1 Why does this not work? Outside of the scope of the loop my changes are lost. #2 In a general sense, is this the right approach? Putting this code in the controller feels like a hack.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
至于为什么它不起作用,我怀疑延迟执行正在让你烦恼。如果像这样包装 Linq 查询
( from ... select p).ToList()
,它将导致查询被评估。至于方法,它是表示层中的数据访问,所以一般来说,这是应该避免的。
As for why it doesn't work, I suspect deferred execution is getting you. If you wrap the Linq query like so
( from ... select p).ToList()
it will cause the query to be evaluated.Regarding the approach, it is data access in the presentation tier, so generally speaking, that would be something to avoid.