ASP.NET MVC模型绑定派生类 [英] Asp.net MVC Model binding derived class

查看:113
本文介绍了ASP.NET MVC模型绑定派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个抽象类PaymentMethod和2个派生类PaymentMethodInvoicePaymentMethodBilling.我为每个人写了共享的EditorTemplates.

I've written an abstract class PaymentMethod and 2 derived classes, PaymentMethodInvoice and PaymentMethodBilling. For each of them I've written shared EditorTemplates.

GET工作正常,我选择我的PaymentMethod并获取正确的表格.如果我发布此表单,则模型绑定不起作用,它将尝试实例化抽象类PaymentMethod.

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.

我必须重写CreateModel 还是有更好的解决方案来解决这个问题?

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

推荐答案

我必须重写CreateModel

Must I override the CreateModel

否.

还是有更好的解决方案

or is there a better solution

否.

在执行方法中的任何代码之前,DefaultModelBinder通过首先初始化模型的实例,然后读取客户端发送的名称/值数据(表单数据,查询字符串值等)来绑定模型.如果在模型中找到匹配的属性名称,它将尝试设置该属性的值.在您的情况下,它会初始化PaymentMethod的实例,因此即使您通过回发与派生类之一关联的其他值,它们也会被扔掉.

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.

您当然可以在该方法中编写代码以手动读取Request.Form值,从这些值中确定要使用的派生类,对其进行初始化并设置其值.但是不仅会在方法中添加很多难看的代码,而且还会丢失模型绑定的所有内置功能,例如ValueProviders,设置ModelState值和错误等,这也是您所需要的实施.

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.

使用推荐的方法粘贴并创建一个覆盖CreateModel()

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

这篇关于ASP.NET MVC模型绑定派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆