开发者

ViewModel's Everywhere!

I'd like to see the SO's community response to this. I understand that a ViewModel is basically used to bind the view with data. When a form submits, should the object that be returned (modelbinded) be a ViewModel or an entity? I know a ViewMod开发者_JAVA百科el IS an entity but I'm talking theoretically here. I want to make sure that myself and my team understand the concepts.


I prefer to give a ViewModel to the view and have the ModelBinder bind to one of my business entities.

My ViewModels often contain little bits of display based data (e.g. whether or not to display widget A) so they don't really need to be bound.

Kindness,

Dan


It's OK to do both as long as you don't compromise the design for the lazyness. E.g. it's not easy to bind to complex entities - one example is if entity does not have parameterless constructor - and if you avoid such entities just to make binding easy... it's bad. It's like making all variables "string" just because your UI control can't understand dates or floats. It may also lead to dumb DTO-like entites and anemic domain model. If, however, you don't need smart entities - it's OK to use them in model binding.

As always, it takes experience and good taste to make a decision. There's no simple rule. One way to avoid UI influence on domain design is to develop domain level first (TDD is a good help here). Another way is to have several "clients" for your domain layer - different requirements will make you extract the core functionality into the domain layer, moving specific things (like presentation attributes and formatting) to appropriate layers / view models.


I use the ViewModel to pass data into the page and to get data out. All my forms to into a ViewModel first, which I'll run any validation I need on, and then I'll convert that to the appropriate DTO/Entity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜