Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC should you create a model for each view?

Tags:

asp.net-mvc

I'm fairly new to ASP.Net MVC and I find myself making a single model class for every view. E.g. SignInModel, SignUpModel, EditProfileModel and so forth.

Many of these are somewhat similar, having the same DB fiels, and then a few custom properties.

Is this really how MVC is supposed to be done, or did I miss some aspect of it ?

I realize this may be subjective, but there ought to be a "best-practice" around this.

like image 413
Steffen Avatar asked Feb 22 '11 11:02

Steffen


1 Answers

Is this really how MVC is supposed to be done, or did I miss some aspect of it ?

That's absolutely how it MVC is supposed to be done and you aren't missing any aspect of it.

A View Model per View.

You could still have base view model classes and use inheritance of your view models but be careful especially with the validation rules which might be different between the different views. So for example if on one view a property was required it might no longer be required on another view so if you have used a base view model class and data annotations you would be pretty much toasted.

Do not for one second hesitate to create view models even if you repeat some properties. That's what view models are meant for => respond to the specific needs of a view and bear in mind that those needs could change quite often, so having separate view models might look difficult at the beginning but at the long term it is the best solution both in terms of maintenance and good practices IMHO.

like image 119
Darin Dimitrov Avatar answered Nov 15 '22 23:11

Darin Dimitrov