I've used some ideas from What is ViewModel in MVC?
I've read a lot of other posts and articles, but haven't read anything that really explains the interactions between them, so my post is pretty involved.
To get to the point I'll start with my questions below, but The Context may explain some of my confusion.
The Question
How does ASP.NET MVC's View Model concept fit in with the whole MVC design pattern? Specifically, what are the interactions between the Domain Models, View Models, Views, and Controllers?
I've never thought about the model being split into View Models and Domain Models, and have really just been using what I think of as Domain Models (is it normal to have both View Models and Domain Models outside of ASP.NET MVC?).
It seems like the View / View Model should depend on one another because they're so specific to each other.
Isn't the idea of MVC to make code more maintainable and reusable? Because the View Model is specific to the View, would it ever be used elsewhere? And if it won't be used elsewhere, wouldn't it be more maintainable to have the view model simply be defined in the View?
The Context
After taking a couple of courses in software design and development, I've learned about architectural design patterns, predominantly MVC. From what I've learned and have implemented in projects (correct me if I'm wrong) is that MVC separates the
- Data / business logic (Model)
- User interface & logic (View)
- Application logic (Controller)
from one another. Furthermore,
- The Model and View use the Controller as a service to transfer data between each other
- Neither the Model or the View know each other
I've recently started an internship where we are using ASP.NET MVC to build our web apps. After working with it for a while, I've obviously noticed that the model splits into two categories: Domain Models and View Models.
To my understanding (again, correct me if I'm wrong):
- Domain Models define real/physical objects
-
View Models define only the data that needs to be displayed in the view or any logic that may be used in displaying data So basically, a user's profile might display their name, age, and bio and have a View Model:
class UserProfileViewModel string Name int Age string Bio
while there might exist a Domain Model
class User
string ID
string Name
string Email
int Age
DateTime DateJoined
Aucun commentaire:
Enregistrer un commentaire