问题
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