有没有为什么默认ModelBinder的不结合领域的一个原因

有没有为什么默认ModelBinder的不结合领域的一个原因

本文介绍了有没有为什么默认ModelBinder的不结合领域的一个原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET MVC3,我想知道,默认ModelBinder的结合公共属性而不是公共领域。

通常我只是定义模型类与属性,但有时我用一些predefined类,其中包含一些字段。每次我都调试和记住ModelBinder的只是不喜欢领域。

问题:请告诉我背后的原因


解决方案

While I cannot answer your question about the exact reason why the default model binder works only with properties (my guess is that it respects better encapsulation this way and avoids modifying internal state of the object which is what fields represent) I can say that what you call predefined classes should normally be view models. You should always use view models to and from your controller actions. Those view models are classes that are specifically defined to meet the requirements of the given view.

So back to the main point: fields are supposed to be modified only from within the given class. They should not be accessed directly from the outside. They represent and hold internal state of the class. Properties on the other hand is what should be exposed to the outside world. Imagine that in the property getter/setter you had some custom logic. By modifying directly the field this custom logic would be broken and potentially bring the object into an inconsistent state.

这篇关于有没有为什么默认ModelBinder的不结合领域的一个原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 04:55