简体   繁体   中英

Asp.net MVC Model binding derived class

I've written an abstract class PaymentMethod and 2 derived classes, PaymentMethodInvoice and PaymentMethodBilling . For each of them I've written 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 tries to instantiate the abstract class PaymentMethod .

Must I override the CreateModel protected override object CreateModel or is there a better solution to handle this?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM