MS MVC3模型绑定对象 [英] MS MVC3 Model Binding an Object
问题描述
有人可以帮助我更好地了解DefaultModelBinder以及它如何处理具有对象类型属性的模型的绑定吗?
Can someone help me better understand the DefaultModelBinder and how it handles binding a Model that has a property of type object?
我已经下载了代码并尝试对其进行跟踪,但是仍然有些挠头.
I've downloaded the code and tried tracing through it, but am still scratching my head a little.
假设我有一个这样的模型:
Let's say I have a Model like this:
public class MyModel{
public object MyProperty{ get; set; }
}
并假设我的所有表单都正确生成(例如:name ="MyModel.MyProperty")
And assume that my forms are all generated correctly (ex: name="MyModel.MyProperty")
将MyProperty的各种情况实际上设置为某些类型的实例会发生什么情况?
What happens for various cases of MyProperty actually being set to instances of certain types?
在我的情况下,我从DefaultModelBinder派生自定义绑定程序,并重写CreateModel()以返回MyProperty设置为正确Type的MyModel.
In my case, I derive a custom binder from DefaultModelBinder and override CreateModel() to return a MyModel with MyProperty set to the correct Type.
我注意到,如果我将MyProperty设置为字符串,则出于某种原因DefaultModelBinder :: BindProperty()会返回具有表单字段内容的大小为1的string [],而不仅仅是字符串.为什么?
I notice that if I set MyProperty to a string, then for some reason DefaultModelBinder::BindProperty(), returns a string[] of size 1 with the contents of the form field, rather than just a string. Why?
如果MyProperty是更复杂的类型,即使我的表单字段都被正确命名(例如:name ="MyModel.MyProperty.FirstName"),绑定也似乎根本不起作用.
If MyProperty is some more complex type, even though my form fields are all named properly (ex: name="MyModel.MyProperty.FirstName") the binding doesn't seem to work at all.
以前有没有人处理过这样的复杂/抽象模型绑定方案?有没有更好的办法? (我知道这很奇怪,但是我确实需要将MyModel的MyProperty作为对象,因为直到运行时我才知道它实际上是什么类型)
Has anyone dealt with a complex/abstract model binding scenario like this before? Is there a better way? (I know it's weird, but I really do need to have MyModel's MyProperty be object because I can't know what Type it actually is until runtime)
推荐答案
考虑使用接口,并为其使用自定义绑定程序.这可能吗?这样,在运行时就不会有未知的对象类型.
Consider using an interface and use a custom binder for it. Is this possible? Then there is no unknown object type at runtime.
这篇关于MS MVC3模型绑定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!