简体   繁体   English

在ASP.NET MVC中使用类型为另一个ViewModel的属性的ViewModel是不好的做法

[英]Is it bad practice to have a ViewModel with a property typed as another ViewModel in ASP.NET MVC

Would it be considered bad practice to have a viewmodel that has a property of another view model?...as in: 拥有一个具有另一个视图模型属性的视图模型会被认为是不好的做法吗?...如:

public class PersonViewModel
{
     public PersonJobViewModel Peron { get; set;}
     //other properties here...
}

EDIT 编辑

A little more about my particular situation: 更多关于我的特殊情况:

I have a view model that currently contains 2 domain classes. 我有一个视图模型,目前包含2个域类。 I pass this viewmodel to a view that loads 2 partials views(one for each domain class in the viewmodel) 我将此viewmodel传递给一个加载2个局部视图的视图(一个用于viewmodel中的每个域类)

So with this I end up passing pure domain models directly into the partial views. 因此,我最终将纯域模型直接传递到局部视图中。

My thinking is that I can make a view model for each domain model that go to the partials...and then wrap those 2 in another viewmodel that gets passed to my parent... 我的想法是,我可以为每个域模型创建一个视图模型,然后将这些2包装到另一个传递给我父模型的视图模型中...

or is there a better way to accomplish this? 或者有更好的方法来实现这一目标吗?

No, it's not bad at all. 不,它一点都不差。 It's perfectly fine code. 这是完美的代码。 It allows you to reuse portions of view models between different views. 它允许您在不同视图之间重用部分视图模型。

I don't believe that I would consider it bad practice to aggregate one ViewModel within another. 我不认为我认为将一个ViewModel聚合在另一个ViewModel中是不好的做法。 I can see an advantage, like being able to render a partial view or use an EditorFor of the aggregated view model. 我可以看到一个优势,比如能够渲染局部视图或使用聚合视图模型的EditorFor

It is definitely okay. 这绝对没问题。 View Models should, in concept, mimic your domain model with relevant information for a given view(s). 在概念上,视图模型应该模拟您的域模型以及给定视图的相关信息。

Just remember that once "best practices" become counter-intuitive and counter-productive they may no longer be the best practice for you in that given scenario. 请记住,一旦“最佳实践”变得违反直觉并适得其反,在特定情况下,它们可能不再是您的最佳实践。 Best practices are guidelines, not strictly adhered to requirements. 最佳实践是指导原则,不严格遵守要求。

Edit: Changed my initial comment because I'm not sure I was clear enough before in saying that it was okay to do. 编辑:更改了我的初始评论,因为我不确定我之前是否已经说清楚可以这么做了。

Edit2: Also ask yourself whether you even need view models. Edit2:还要问问自己是否需要查看模型。 If they literally mimic your domain models, what's the point? 如果他们真的模仿你的领域模型,重点是什么? Just use your Domain Model (unless you have other dependencies that would make this ugly). 只需使用您的域模型(除非您有其他依赖项会使这个丑陋)。

No, you may have partner model vs some fields like: 不,你可能有合作伙伴模型和一些领域,如:

public class Parner
{
  int age {get; set;}
  //etc
} 

public class ParnerList
{
  public List<Partner> ListOfPartner {get; set;}
  public int PageNumber {get; set;}
  public int PageCount {get; set;}
  //etc
}

It's easy to use in View for show list vs paging 它很容易在View for show list和paging中使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM