Ian Warburton
Ian Warburton

Reputation: 15676

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

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.

Upvotes: 2

Views: 3477

Answers (2)

Julius
Julius

Reputation: 946

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

Upvotes: 1

Fatih Türker
Fatih Türker

Reputation: 135

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

Upvotes: 0

Related Questions