michael
michael

Reputation: 647

Should ViewModels stay in UI layer or move it to another layer?

I have UI layer (with ASP.NET MVC), BLL layer, DAL layer and Model layer. Model layer has got POCO classes which represents tables in database.

UI, BLL and DAL layers have got references to Model layer.

In UI layer I often use POCO classes from Model layer to display something users. But when users can do something using forms then I often create ViewModels with validation attributes.

Should I put ViewModels in UI layer or move ViewModels to Model layer?

Upvotes: 0

Views: 567

Answers (3)

wm1sr
wm1sr

Reputation: 2015

I take the view model as a translator of the data behind to the UI. I make a view model for each page, so that all controls in this page has something to bind to. For me, it makes sense to group pages with their respective view model. It looks like this:

Project folders

Or even better, nest the view and the view model files using a tool like NestIn:

Project folders

Upvotes: 0

David Shorthose
David Shorthose

Reputation: 4497

I personally create my viewmodels in a different project and include them in the required layers that need to access them. This way I can then reuse the viewmodels in other projects.

I typically have my projects setup like this:

MVC Project (UI)
MVC ViewModels (UI/Service Layer) Service Layer + Logic Layer (Repositories) Database Models (ORM(Telerik DataAccess) Layer)

This way I can hide all my database models behind the service layer and only pass the viewmodels between the UI and service layer.

But this is how I prefer to work. I am sure there are others that may disagree with my project set up but this to me seems logical.

It really comes down to your needs. If you find you are converting your DB models to the viewmodels in your UI layer then I would suggest moving them out so that you can do all this conversion within your service layer(s).

Upvotes: 0

RyanB
RyanB

Reputation: 757

This is really a matter of preference, but I prefer to keep my Model classes (that map to the database) separate from ViewModels. This way I don't get confused about what maps to the database and what doesn't.

Upvotes: 3

Related Questions