Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put ViewModel classes in MVC

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?

like image 413
Vivendi Avatar asked Feb 12 '14 08:02

Vivendi


People also ask

Where do you put ViewModels?

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. Show activity on this post.

How do I add a model class to a view?

Go to solution explorer => Views Folder => Right-click on “Model” Folder >> go to “Add” >> Click on [Class] as follow. Provide the required name like “Product. cs” then click on “Add” button as follow.

What is the need of ViewModel in MVC?

ViewModel = Model that is created to serve the view. ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible. ViewModel serves this purpose. View Model is a model class that can hold only those properties that are required for a view.

What is a ViewModel class?

ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment . It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).


2 Answers

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.

like image 177
yohannist Avatar answered Oct 06 '22 00:10

yohannist


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

like image 29
owenrumney Avatar answered Oct 05 '22 23:10

owenrumney