TOC

The community is working on translating this tutorial into Georgian, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Models:

Introduction

In the previous chapters, we have gone more in depth with both the C (Controller) and the V (View) of the MVC pattern, so in this chapter, we'll focus on the M (Model). We're talking about it last because you can actually have a website based on the MVC pattern without using a Model, although that would be a pretty simple website.

What is a Model?

As we discussed in the quick start part of this tutorial, where we quickly added a Controller, a View and a Model to our project, the Model in an MVC application should represent the current state of the application, as well as business logic and/or operations. A Model can be any kind of object found in the framework. It could in fact be a simple number or string, or it could be a complex object instantiated from a class, e.g. a User class which holds information about a user, a GuestbookEntry item which contains a post to a guestbook or anything else. That also means that your Model can be a class you already have, e.g. something that comes from the database, or a class that you create specifically to become a Model for one or several Views.

A very important aspect of the MVC pattern is the Separation of Concerns. SoC is achieved by encapsulating information inside a section of code, making each section modular, and then having strict control over how each module communicates. For the MVC pattern, this means that both the View and the Controller can depend on the Model, but the Model doesn't depend on neither the View nor the Controller. This turns your Models into a module that can exist even outside of the MVC framework, e.g. for use in a desktop application, and then it has the added benefit of allowing your Models to be tested without the visual representation, e.g. through the use of unit tests.

As mentioned, the Model can be a class already defined in your project, or it can be a new class you add specifically to act as a Model. Therefore, Models in the ASP.NET MVC framework usually exists in a folder called "Models", or they come from outside of the project, e.g. from a class library. A Model doesn't have to inherit from a specific base class or anything like that - they are truly just regular .NET classes. There are a couple of ways to enrich your Model classes with MVC-related information though, but we'll discuss that later.

Summary

The Model in an MVC application should represent the current state of the application, as well as business logic and/or operations. In the upcoming articles of this chapter, we'll dig deeper into the more advanced, Model-related subjects.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!