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.

2
  • 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. Commented May 22, 2011 at 17:14
  • please tell me there's a better way!! Commented Jun 26, 2011 at 16:33

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.