The Model-View-Controller (MVC) design pattern has existed for years. (http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html) ASP.Net developers have been implementing it for years either through their own custom code or via third-party frameworks such as Monorail (http://www.castleproject.org/monorail/index.html).
Recently, Microsoft released the ASP.Net MVC framework to give web developers the option of using this design pattern without the need for a lot of “plumbing” code or the use of a third-party framework.
The Model-View-Controller design pattern splits an application into three distinct parts called (you guessed it) “Models”, “Views” and “Controllers”.
A Model represents the stateful data in an application. These are often represented as objects such as “Customer” and “Employee” that represent an abstract business object. For persistent data, the Model may save and retrieve data to and from a database. Public properties of these objects (for example, “LastName” or “HireDate”) represent their state at any give time. The model objects have no visual representation and no knowledge of how they will be displayed on screen.
A View is the application’s user interface (UI). In a web application, this is the web page that the user sees and clicks and interacts with directly. The View can display data but it has no knowledge of where the data it displays comes from.
A Controller is the brains of your application. It links the Model to the View. It handles communication between the other two parts of the application. It is smart enough to detect when a data needs to be retrieved (from the model) and refreshed (in the view). It sends updated data from the view back to the model so that the model can persist it.
This separation of the various concerns of the application encourages developers to create loosely-coupled components.
Much of the communication to the controller occurs by raising events in the view, which keeps the controller loosely coupled from the other parts. However the real advantage of the MVC pattern is that, because they only communicate through the controller, the model and view are very loosely coupled. This provides the following advantages to an MVC application.
- Loosely-coupled applications have fewer dependencies, making it easier to switch the user interface or backend at a later time.
- Applications can be tested more easily, because so little code is in the view. We can test our code by writing unit tests against the controller.
In the next article, we will look at how to create a Microsoft ASP.Net MVC application.