2

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

  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.

Ian Warburton
  • 15,170
  • 23
  • 107
  • 189
  • Well I've gotten things working by having two unrelated contact view models, two different partial views, no typing of the main web page's model and lots of 'if' statements in the controller. I guess MVC doesn't accommodate polymorphism in some key locations! You can see that the model binder doesn't take into account the runtime type of a model because in the MVC source code one can see it looking up the type information based on the type parameters and not the type of the passed in object. – Ian Warburton May 22 '11 at 17:14
  • please tell me there's a better way!! –  Jun 26 '11 at 16:33

2 Answers2

1

I think you will need to create your own ModelBinder. Take a look at ASP.NET MVC 3: DefaultModelBinder with inheritance/polymorphism.

Community
  • 1
  • 1
Julius
  • 946
  • 1
  • 10
  • 26
0

You can try to implement common Interface for both contact entity. And use that Interface in Action parameter , validate against Interface.

Fatih Türker
  • 135
  • 1
  • 8