In the beginning of this tutorial, we briefly talked about Controllers in the MVC pattern and we even added one to our project, to see what it looks like and what it does, to get you quickly up and running. In this chapter, we'll go more in depth with the topic of Controllers, starting in this article, where we'll go over the core concepts of a Controller.
What is a Controller?
As mentioned in the start of this tutorial, the Controller acts as the middleman - it will combine your Model with a View and serve the result to the end-user. However, neither a Model nor a View is required - the Controller can act on its own for the most basic operations, e.g. delivering a simple text message or redirecting the user to somewhere else. We'll discuss this in the later article on Action Results.
In ASP.NET MVC, a Controller is just like any other class, so it has a .cs file extension (or .vb, if you use Visual Basic) and looks like any other .NET class. However, there are a few things that will allow you (and the .NET framework) to recognize it as an MVC Controller:
- It's usually placed in a folder called "Controllers" in the root of your project
- It inherits from Microsoft.AspNetCore.Mvc.Controller (or from one of your own classes which then inherits the Microsoft.AspNetCore.Mvc.Controller class)
- The name of the class will usually end with the word Controller, e.g. "HomeController" or "ProductsController"
If you don't follow these conventions, the .NET framework will not be able to recognize your class as a Controller, so it makes sense to follow them. However, if you insist on e.g. naming your Controller classes differently, you can decorate it with the [Controller] attribute, placed right before the class declaration.
By inheriting the Microsoft.AspNetCore.Mvc.Controller class, you get some added functionality that you can use for MVC purposes, e.g. the ability to return Views/Partial Views. It also allows your Controller class to access HTTP related information like the querystring, thanks to the HttpContext property on the Controller class. In other words, it turns a regular .NET class into a web-aware class, allowing you to do stuff you would normally be able to do in your PHP or ASP Classic file or any of the many other web technologies out there.
Where are Controllers placed?
As mentioned, Controllers are usually placed in a folder called "Controllers", directly in the root of your MVC project. They are usually named based on their purpose, with the word "Controller" as a suffix. In the Solution Explorer, the folder structure could look something like this:
Hopefully you now have a better understanding of what a Controller is and how they are defined. In the upcoming articles of this chapter, we'll dig deeper into the various Controller-related subjects, so that you will hopefully get the full idea of all the things you can do with a Controller in ASP.NET MVC.