I’ve read a few articles about MVC but there’s one thing that isn’t clear to me. What is the role of the model in practical term.
Does the model represent the business object?
Or is it just a class that help send information from the controller to the view?
Take for example two business class (data populated from the database)
Class Image
Property FileName As String
Property CreatedBy As User
End Class
Class User
Property UserName as String
End Class
Will “Image” be the model or should I create a new class?
In the model, should I create a UserName property that will fetch it’s data from the User object?
Class ImageModel
Property FileName As String
Property CreatedBy As User
ReadOnly Property UserName As String
Get
Return User.UserName
End Get
End Property
End Class
There are many views on this, but in my experience, there are 2 major views of the
Model:ViewModel
This is a POCO that simply contains all the data necessary to display the
View. The data is usually populated by theController.Fat Model, Skinny Controller
The
Modeldoes the majority of the business-work. It contains and populates all the data that is needed by theView, and is used by theControllerto save data, etc.The beauty of MVC
The beauty of MVC is that it’s OPEN! You can choose any type of model you want … you can put all your data into
ViewState, into aModel, into aViewModelthat contains a bunch ofModels, whatever. It’s really up to you. The Model, View, and Controller are blank canvases that can be used however you like.What I use
My team has done a lot of MVC work, and we have tried many of these different methods. We finally decided that our favorite was the Fat Model, Skinny Controller paradigm.
I believe that this pattern is the best at "keeping it simple" and "don’t repeat yourself", and it definitely maintains the "separation of concerns".
Here’s how our code is organized:
Model, and gives theModelto the view. Does NOT access Business or Data layers.ModelView, and populates itselfEven though this sounds like a generic principle of MVC, it quickly becomes obvious that MVC does not require these principles, which is why many projects use other principles.
Example
Here’s an example
Model. The Controller creates it, it populates itself, and the Controller passes it to the View.All the "user business logic" in this case is in a different project (our "Business Layer"), because we have a large system. But smaller projects don’t require this … the Model can contain business logic, and even data-access code.