开发者

ASP.net MVC problems when model binding with sub-class

开发者 https://www.devze.com 2023-03-07 08:23 出处:网络
I\'ve got two types of contact entity. One that just has an email address and one that drives from this and includes fie开发者_开发知识库lds for a postal address.

I've got two types of contact entity. One that just has an email address and one that drives from this and includes fie开发者_开发知识库lds 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...

  1. 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.

  2. 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消