Asp.net MVC Model binding derived class

守給你的承諾、 提交于 2019-12-11 12:13:27

问题


I've write an abstract class PaymentMethod and 2 derived classes, PaymentMethodInvoice and PaymentMethodBilling. For each of them i've write shared EditorTemplates. The GET works fine, I select my PaymentMethod and get the right form. If I POST this form the model binding doesn't work, it trys to instantiate the abstract class PaymentMethod.

Must I override the CreateModel (protected override object CreateModel)[1] or is there a better solution to handle this?

[1] MVC 3 Model Binding a Sub Type (Abstract Class or Interface)


回答1:


Must I override the CreateModel

No.

or is there a better solution

No.

Before any code in you method is executed, the DefaultModelBinder binds you model by first initializing an instance of your model and then reading the name/value data sent by the client (form data, query string values etc). If it finds a matching property name in your model, it will attempt to set the value of that property. In your case, it initializes an instance of PaymentMethod, so even through you may be posting back additional values associated with one of the derived classes, they are just tossed away.

You could of course write code in the method to manually read the Request.Form values, determine from those values which derived class to use, initialize it, and set its values. But not only would you be adding a lot of ugly code inside your method, you would be missing out on all the built in features of model binding such as ValueProviders, setting ModelState values and errors etc. which you would also need to implement.

Stick with the recommended approach and create a custom model binder that overrides CreateModel()



来源:https://stackoverflow.com/questions/33819276/asp-net-mvc-model-binding-derived-class

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