asp.net MVC应该使用视图模型封装域模型吗? [英] asp.net MVC should a View-Model Encapsulate Domain-Model?
问题描述
我已经看到了很多MVC示例,其中将域对象直接传递到视图,如果您的视图很简单,这将很好地工作.
I've see a lot of MVC examples where domain-objects are passed directly to views, this will work fine if your view is simple.
常见的替代方法是拥有一个视图模型,该模型具有与域模型相同的所有属性,以及视图可能需要的任何其他属性(例如"confirmPassword").
The common alternative is to have a view-model which has all the same properties as your domain-model + any extra properties your view may need (such as 'confirmPassword').
在进行大量阅读之前和发现AutoMapper之前,我开始创建自己的视图模型变体,其中域对象(或多个域对象)只是视图模型的属性.
Before doing too much reading and before discovering AutoMapper I started creating my own variant of view-model where the domain-object (or multiple domain objects) are simply properties of the view-model.
我做了一件坏事吗?这种方法可以带来什么问题或好处? 在什么情况下,这种处理方式可能会运作良好?
Have I done a bad thing? What problems or benefits could be derived from this approach? Under what circumstances might this way of doing things work well?
推荐答案
直接将域模型公开给视图并没有什么本质上的坏处.主要风险来自公开您不想要的属性,例如Employee对象上的薪金字段.如果要返回JSON,请务必注意这一点.
There's nothing inherently bad about exposing your domain model directly to the view. The primary risk comes from exposing a property you didn't mean to, like a salary field on an Employee object. Be sure to watch out for this if you're returning JSON.
要注意的另一件事是当您从编辑表单绑定回来时.您应该了解特定的涉及的风险.基本上,恶意用户可以向POST添加字段,这些字段恰巧与您并非可编辑的字段相匹配.我总是绑定到传递给服务的中间对象,然后再将其映射回域.
Another thing to watch out for is when you're binding back from an edit form. You should be aware about the specific risks that are involved. Basically a malicious user could add fields to the POST that happen to match fields that you didn't mean to be editable. I always bind to an intermediary object which is passed into a service before mapping it back to the domain.
这篇关于asp.net MVC应该使用视图模型封装域模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!