模型与子类绑定时的 ASP.net MVC 问题
我有两种类型的联系人实体。一种只有电子邮件地址,另一种则从该地址驱动并包含邮政地址字段。
我正在尝试使我的控制器操作适用于任一类型的联系人,但到目前为止遇到了两个问题...
当使用 DataAnnotations 进行验证时,其验证基类中的字段之前子类中的字段。我实际上希望这一切以相反的顺序发生。有没有办法重新安排一下顺序?当然,通常情况下,人们可以只更改字段的顺序,但如果字段位于不同的类中,则这是不可能的。
我发现我需要手动创建模型,因为默认模型绑定器似乎只想创建操作参数中指定的特定类型。当我尝试使用“UpdateModel”手动绑定模型时,即使它只绑定基本类型字段(基本类型是我的联系人工厂返回的类型)。
有人对此有什么建议吗?看起来我将不得不恢复到不断评估正在操作的联系人类型的意大利面条代码。
干杯,伊恩。
I've got two types of contact entity. One that just has an email address and one that drives from this and includes fields for a postal address.
I'm trying to make my controller action work with either type of contact and have so far stumbled into two problems...
When validation occurs using DataAnnotations, its validating fields from the base class before the fields from the sub-class. I actually want this to happen in the opposite order. Is there anyway to re-arrange the order? Usually of course one could just change the order of the fields but if the fields are in different classes this isn't possible.
I've found I've needed to create the model manually because the default model binder only seems to want to create the specific type specified in the action's parameter. When I try and bind the model manually with 'UpdateModel' even then its only binding the base type fields (the base type is the type being returned by my contact factory).
Any one have any advice on doing this? It looks like I'm going to have to revert to spaghetti code that constantly evaluates the type of contact being operated on.
Cheers, Ian.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您需要创建自己的 ModelBinder。查看 ASP.NET MVC 3:具有继承/多态性的 DefaultModelBinder。
I think you will need to create your own ModelBinder. Take a look at ASP.NET MVC 3: DefaultModelBinder with inheritance/polymorphism.
您可以尝试为两个联系人实体实现通用接口。并在操作参数中使用该接口,针对接口进行验证。
You can try to implement common Interface for both contact entity. And use that Interface in Action parameter , validate against Interface.