MS MVC3 模型绑定对象
有人可以帮助我更好地理解 DefaultModelBinder 以及它如何处理绑定具有对象类型属性的模型吗?
我已经下载了代码并尝试跟踪它,但我仍然有点摸不着头脑。
假设我有一个像这样的模型:
public class MyModel{
public object MyProperty{ get; set; }
}
并假设我的表单全部正确生成(例如:name="MyModel.MyProperty")
MyProperty 的各种情况实际上被设置为某些类型的实例会发生什么?
就我而言,我从 DefaultModelBinder 派生自定义绑定器并重写 CreateModel() 以返回 MyModel,并将 MyProperty 设置为正确的类型。
我注意到,如果我将 MyProperty 设置为字符串,则出于某种原因 DefaultModelBinder::BindProperty(),会返回一个大小为 1 的 string[] 以及表单字段的内容,而不仅仅是一个字符串。为什么?
如果 MyProperty 是一些更复杂的类型,即使我的表单字段都正确命名(例如:name =“MyModel.MyProperty.FirstName”),绑定似乎根本不起作用。
以前有人处理过这样的复杂/抽象模型绑定场景吗?有更好的办法吗? (我知道这很奇怪,但我确实需要让 MyModel 的 MyProperty 成为对象,因为直到运行时我才知道它实际上是什么类型)
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; }
}
And assume that my forms are all generated correctly (ex: name="MyModel.MyProperty")
What happens for various cases of MyProperty actually being set to instances of certain types?
In my case, I derive a custom binder from DefaultModelBinder and override CreateModel() to return a MyModel with MyProperty set to the correct Type.
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?
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.
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
考虑使用接口并为其使用自定义绑定器。这可能吗?那么运行时就不存在未知的对象类型了。
Consider using an interface and use a custom binder for it. Is this possible? Then there is no unknown object type at runtime.