使用 ViewModel 显示 MVC 中的所有项目

发布于 2024-12-10 11:39:23 字数 542 浏览 1 评论 0原文

我有一个显示实体列表 (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷血 2024-12-17 11:39:23

IEnumerable 是推荐的方式。我见过很多人这样定义他们的视图模型:

public class MyViewModel
{
    public SomeDomainEntity1 Entity1 { get; set; }
    public SomeDomainEntity2 Entity2 { get; set; }
    public IEnumerable<SomeDomainEntity3> Entities3 { get; set; }
}    

实际上,这不是视图模型的正确用法。对我来说这根本不是视图模型。视图模型不应引用任何实体域模型。

IEnumerable<ViewModel> is the recommended way. I have seen many people defining their view models like this:

public class MyViewModel
{
    public SomeDomainEntity1 Entity1 { get; set; }
    public SomeDomainEntity2 Entity2 { get; set; }
    public IEnumerable<SomeDomainEntity3> Entities3 { get; set; }
}    

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.

诺曦 2024-12-17 11:39:23

如果您只需要来自可枚举的信息,则将其直接传递给视图没有任何问题。如果您需要一些额外的信息(例如:当前用户或任何其他信息),您应该将可枚举作为 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文