Where to put ViewModel classes in MVC
Asked Answered
G

3

15

My question is very simple. I want to know where to put my ViewModels in an MVC application.

Currently the project I'm working on only has ViewModels and they are stored in the Models folder. In that folder we directly create ViewModel classes.

But normally I would also have Model classes, to get data from a database or something. Then from a Controller I'd 'talk' to a Model method and store the result in a ViewModel property.

But where do I put the Model classes and ViewModel classes when I use both of them? What is a good practice in the sense of structuring my files/folders for these two?

Gaultheria answered 12/2, 2014 at 8:5 Comment(3)
I see no problem in having a ViewModel folder. There are no constraints which state that the Model folder should be present.Donatus
@AndreiV I know, but I have both now. So is it 'normal' to put a ViewModel in a ViewModels folder and a Model in a Models folder?Gaultheria
I would go with ViewModel as a sub folder Model, if you're using both to display data in the views. If not, separate folders would make more sense to me.Donatus
C
17

Just create a new folder called ViewModels inside your project. So that along with the Views, Controllers and Models folders, you'll also have ViewModels. Like you already said, you talk to your DAL using your models and you talk to your views using your view models.

Competency answered 12/2, 2014 at 8:22 Comment(0)
M
3

You need to structure your files and folders in a way that you and the people that follow you will find intuitive and maintainable.

I don't think there is any hard and fast rules about folder structure, just some are a lot worse than others. If it seems illogical and a bit smelly, then it probably is.

What you're proposing seems fine

Marinetti answered 12/2, 2014 at 8:23 Comment(0)
T
0

Create seperate folder"ViewModels" and refer the namespace in controller and refer the same in the respective view

Trilly answered 13/7, 2016 at 14:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.