[英]Asp.net MVC Model binding derived class
I've written an abstract class PaymentMethod
and 2 derived classes, PaymentMethodInvoice
and PaymentMethodBilling
.我编写了一个抽象类
PaymentMethod
和 2 个派生类, PaymentMethodInvoice
和PaymentMethodBilling
。 For each of them I've written shared EditorTemplates
.对于他们中的每一个,我都编写了共享的
EditorTemplates
。
The GET works fine, I select my PaymentMethod
and get the right form. GET 工作正常,我选择我的
PaymentMethod
并获得正确的表格。 If I POST this form the model binding doesn't work, it tries to instantiate the abstract class PaymentMethod
.如果我 POST 此表单模型绑定不起作用,它会尝试实例化抽象类
PaymentMethod
。
Must I override the CreateModel protected override object CreateModel
or is there a better solution to handle this?我必须覆盖 CreateModel
protected override object CreateModel
还是有更好的解决方案来处理这个问题?
Must I override the CreateModel
我必须覆盖 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).在执行方法中的任何代码之前,
DefaultModelBinder
通过首先初始化模型的实例然后读取客户端发送的名称/值数据(表单数据、查询字符串值等)来绑定模型。 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.在您的情况下,它初始化
PaymentMethod
一个实例,因此即使您可能发回与派生类之一关联的其他值,它们也只是被丢弃了。
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.您当然可以在方法中编写代码来手动读取
Request.Form
值,从这些值中确定要使用哪个派生类,对其进行初始化并设置其值。 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.但是,您不仅会在方法中添加大量难看的代码,还会错过模型绑定的所有内置功能,例如
ValueProviders
、设置ModelState
值和错误等,您还需要实现这些功能。
Stick with the recommended approach and create a custom model binder that overrides CreateModel()
坚持推荐的方法并创建一个覆盖
CreateModel()
的自定义模型绑定器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.