MS MVC3 Model Binding an Object

被刻印的时光 ゝ 提交于 2019-12-24 01:48:22

问题


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)


回答1:


Consider using an interface and use a custom binder for it. Is this possible? Then there is no unknown object type at runtime.



来源:https://stackoverflow.com/questions/6809159/ms-mvc3-model-binding-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!