The Controller's Role

It's probably best to start out with a quick definition and then dive into detail from there. Keep this definition in mind while reading this chapter. It will help to ground the discussion ahead with what a controller is all about and what it's supposed to do.

Controllers within the MVC pattern are responsible for responding to user input, often making changes to the model in response to user input. In this way, controllers in the MVC pattern are concerned with the flow of the application, working with data coming in, and providing data going out to the relevant view.

Way back in the day, web servers served up HTML stored in static files on disk. As dynamic web pages gained prominence, web servers served HTML generated on the fly from dynamic scripts that were also located on disk. With MVC, it's a little different. The URL tells the routing mechanism (which you'll begin to explore in the next few chapters, and learn about in depth in Chapter 9) which controller class to instantiate and which action method to call, and supplies the required arguments to that method. The controller's method then decides which view to use, and that view then renders the HTML.

Rather than having a direct relationship between the URL and a file living on the web server's hard drive, there is a relationship between the URL and a method on a controller class. ASP.NET MVC implements the front controller variant of the MVC pattern, and the controller sits in front of everything except ...

Get Professional ASP.NET MVC 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.