有没有为什么默认ModelBinder的不结合领域的一个原因? [英] Is there a reason why the default modelbinder doesn't bind to fields?

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

问题描述

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

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

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


解决方案

  

但有时我用一些predefined类,其中包含一些字段


虽然我不能回答你关于为什么默认的模型绑定与属性只工作的确切原因的问题(我的猜测是,它尊重了更好的封装这种方式避免了修改它是对象的哪些字段重新present的内部状态)我可以说,你所说的 predefined类的一般应视图模型。你应该总是使用视图模型,并从您的控制器操作。这些视图模型是专门定义为满足给定观的要求类。

因此​​,回到主穴:字段应该是只修改了从给定的类中。他们不应该直接从外部访问。他们重新present并持有类的内部状态。另一方面属性是什么应该暴露给外界。试想一下,在属性的getter / setter你有一些自定义逻辑。通过直接修改该领域的定制逻辑将被打破,并可能带来物体进入不一致的状态。

I'm using ASP.NET MVC3 and i'm wondering that the default modelbinder binds to public properties but not to public fields.

Normally i just define the model classes with properties but sometimes i use some predefined classes which contains some fields. And everytime i have to debug and remember that the modelbinder just don't like fields.

The question: Whats the reason behind it?

解决方案

but sometimes i use some predefined classes which contains some fields

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的不结合领域的一个原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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