使用 ViewModel 显示 MVC 中的所有项目
我有一个显示实体列表 (L2Sql) 的视图,我已经有一个包含一些用于编辑/查看的属性的 ViewModel。是否建议将 IEnumerable 传递到 View 中以列出所有实体,还是谨慎传递 ViewModel 列表?
HTMS
更新:基于响应,这里是我的 ViewModel:
public class CategoryViewModel
{
#region Properties
public IEnumerable<CategoryViewModel> Categories { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public int Order { get; set; }
public int? ParentCategoryId { get; set; }
#endregion
}
类别属性由视图用于下拉列表,这是可以接受的吗?
I have a View that displays a list of entities (L2Sql), I already have a ViewModel that contains some of the properties for editing/viewing. Is it recommended to pass an IEnumerable into the View to list all entities, or would it be prudent to pass in a list of ViewModel?
HTMS
UPDATE: Based on resopnses here is my ViewModel:
public class CategoryViewModel
{
#region Properties
public IEnumerable<CategoryViewModel> Categories { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public int Order { get; set; }
public int? ParentCategoryId { get; set; }
#endregion
}
The Categories property is used by Views for a dropdownlist, would this be acceptable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IEnumerable
是推荐的方式。我见过很多人这样定义他们的视图模型:实际上,这不是视图模型的正确用法。对我来说这根本不是视图模型。视图模型不应引用任何实体域模型。
IEnumerable<ViewModel>
is the recommended way. I have seen many people defining their view models like this:Actually that's not proper usage of view models. That's not view models at all for me. A view model should not reference any entity domain model.
如果您只需要来自可枚举的信息,则将其直接传递给视图没有任何问题。如果您需要一些额外的信息(例如:当前用户或任何其他信息),您应该将可枚举作为 ViewModel 中的属性。
If you only need the information from the enumerable, there's nothing wrong passing it directly to the view. If you need some extra informations (ex: current user or any other thing), you should put your enumerable as a property in your ViewModel.