什么是建设一个ViewModel适当的粒度? [英] What is the appropriate granularity in building a ViewModel?

查看:133
本文介绍了什么是建设一个ViewModel适当的粒度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个新项目,并看到一些previous项目,这并不能阻止他们的模型(特别是使用MVC提供视足够分离的困难后 - 的模型和视图开始渗入对方位),我想用MVVM。

I am working on a new project, and, after seeing some of the difficulties of previous projects that didn't provide enough separation of view from their models (specifically using MVC - the models and views began to bleed into each other a bit), I wanted to use MVVM.

我理解的基本概念,我很高兴能开始使用它。然而,一件事,脱离了我一点 - ?哪些数据应在视图模型包含

I understand the basic concept, and I'm excited to start using it. However, one thing that escapes me a bit - what data should be contained in the ViewModel?

例如,如果我创建一个视图模型,将包含两个数据,使他们能够以一种形式进行编辑,我抓住它是这样的:

For example, if I am creating a ViewModel that will encompass two pieces of data so they can be edited in a form, do I capture it like this:

public PersonAddressViewModel {
    public Person Person { get; set; }
    public Address Address { get; set; }
}

或者是这样的:

public PersonAddressViewModel {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string StreetName { get; set; }
    // ...etc
}

对于我来说,第一个感觉,我们正在试图做更正确。如果我们做更细粒度的形式(也许所有我们捕捉了名字,姓氏,和的StreetAddress),那么它可能会更有意义,深入到这一水平。但是,我觉得首先是正确的,因为我们捕捉表格中的所有个人数据和所有地址数据。现在看来似乎没有什么意义(和很多额外的工作),为了将东西拆开这样的。

To me, the first feels more correct for what we're attempting to do. If we were doing more fine grain forms (maybe all we were capturing was FirstName, LastName, and StreetAddress) then it might make more sense to go down to that level. But, I feel like the first is correct since we're capturing ALL Person data in the form and ALL Address data. It seems like it doesn't make sense (and a lot of extra work) to split things apart like that.

鸭preciate任何见解。

Appreciate any insight.

推荐答案

如果您使用的是Person对象的所有字段,然后没有什么错误使用一个复杂的视图模型。但是,如果你只使用一个字段在这里或那里,那么它的好多了,只有那些你正在使用的值来构建视图模型。

If you are using all the fields of the Person object, then there's nothing wrong with using a complex view model. However, if you are only using a field here or there, then it's much better to build your viewmodel with only those values you are using.

您可以做你的视图模型,你喜欢的任何方式,但让他们整个的一点是,视图模型应该进行定制,以它的重新presenting的看法。

You can do your view models any way you like, but the whole point of having them is that a view model should be customized to the view it's representing.

它也可以是一个更容易使用第一种方法,如果你使用类似AutoMapper映射到企业或域模型,因为对象应该有类似的定义。

It can also be a lot easier to use the first method if you're using something like AutoMapper to map to business or domain models, because the objects should have similar definitions.

这篇关于什么是建设一个ViewModel适当的粒度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆