Jonathan
Jonathan

Reputation: 26619

Am I needlessly duplicating models in MVC ASP.NET?

I have just started an MVC project for the first time, and I have encountered a problem that I really wasn't expecting: Too many models.

Not too many different models, but too many which are subtly different, but almost exactly the same.

I have a fairly complex page, with several combo boxes, a list of detail objects and some other extraneous unrelated things that I need to keep track of. More information goes to the view than I get back (which is fine).

I have a domain model, which has remained constant throughout. (1 model)

I have a single use view model, which is the domain model and some extra information wrapped round it. (1 model)

I have a single use form model, which is a copy of the view model with an empty shell copy of the domain model inside it with validation stuff on it. (2 models)

I needed to change the type of a property this afternoon, and I had three separate places to change it in. It seems that I have too many models which are single use. It seems so much work for something that was supposed to be much easier than classic ASP.NET.

My question is: Am I doing it right? Are there supposed to be a multitude of models, or am I missing something obvious?

Upvotes: 3

Views: 108

Answers (1)

aaronrhodes
aaronrhodes

Reputation: 616

Not entirely sure what the form model in your example is for - are you using that to limit the post-able fields from the client or using that to map in to your domain?

In my own MVC websites I will have a domain model (which may just be a local domain or come from a remote WCF service) which I map one to one in to my individual ViewModels in order to render on screen and receive the post back. These also contain my validation (be it annotations or fluent etc).

Any property name changes would then be restricted to just the relevant page's ViewModel and the domain.

If you're in a situation where you're replicating properties between domain models then some sort of base view model structure would serve you well for common entities but on the whole it's not something I find to be a massive overhead personally.

Upvotes: 1

Related Questions