直接绑定域模型是个坏主意吗? [英] Is binding domain models directly a bad idea?

查看:78
本文介绍了直接绑定域模型是个坏主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,如果将绑定模型直接作为动作方法中的参数视为一个坏主意?

I'm curious if binding models directly as parameters in the action method is considered as bad idea ?

如果表单变得复杂,我可以创建一个自定义模型活页夹.

If the form gets to complex, I could create a custom model binder.

使用这种方法是否有陷阱?

Are there any pitfals using this approach ?

我想避免创建viewmodel,因为我想让我的应用程序尽可能简单.我想避免将代码和modelview复制到模型绑定.

I'd like to avoid creating of viewmodel, because I want to keep me app as simple as possible. I'd like to avoid of duplicating the code and the modelview to model binding.

推荐答案

我建议几乎总是使用视图模型.

I'd advise to almost always use view models.

如果您使用的是默认对象模板...它们实际上并不像非平面模型一样,虽然您可以覆盖它们,但这并不总是一个好主意.域模型通常不是平坦的.无论哪种方式,使用ViewModel都可以更轻松地基于ModelMetaData进行操作.

If you're using the default object templates... they don't really like non-flat models, and while you could override them, it's not always a good idea. Domain Models are usually not flat. Either way, anything based on ModelMetaData is easier with a ViewModel.

使用ViewModel进行验证也更容易,因为您拥有更加集中的模型,有时验证只在某些视图中有意义.

Validation is also easier with a ViewModel, as you've got a more focused model, and sometimes there's validation that only makes sense in some views.

与使用JsonResult发送模型相比,创建ViewModels更好,更安全..............................................................................但是,当您准备好ViewModel时,使用JsonResult会更容易.当您习惯在任何地方使用域模型时,更容易犯错误并暴露敏感信息.

Creating ViewModels is much better and safer then sending models using JsonResult... Well... you should NEVER send Domain Models outside anyway, even if you're not using ViewModels. But it's easier using JsonResult when you've got a ViewModel ready. It's also easier to make mistakes and expose sensitive information when you're used to using your domain models everywhere.

更改有时更容易,因为更改域模型上的属性并不意味着您必须更改所有视图,只需更改ViewModel的创建即可(如果您使用某种映射器,那只是一个更改)绑定),尽管这不是IMO的重点.

Changes are sometimes easier, because changing a property on the Domain Model doesn't mean you have to change all your views, just change the creation of the ViewModel (if you're using some kind of mapper, that's just one change to the binding), although this isn't a very strong point IMO.

其他一些好处是将表示层与业务层分离,如果您使用的是EF或非poco对象,则在视图中使用它们将变得更加困难.

Some other benefits are decoupling the presentation layer from the business layer, and if you're using EF or non-poco objects, it'll be harder to use them in views.

如果要消除代码重复,可以考虑创建自动创建ViewModel的过滤器,即使没有使用映射器的动作过滤器也可以消除很多代码重复.

If you want to eliminate duplication of code, you could consider creating filters that automatically create your ViewModels, and even without action filters using a mapper does eliminate a lot of code duplication.

顺便说一句,我不认为创建自定义模型联编程序比使用ViewModels更为简单.

BTW, I don't see how creating a custom model binder is simpler than using ViewModels.

这篇关于直接绑定域模型是个坏主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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