Controllers in ASP.NET MVC Application

Controllers in ASP.NET MVC Application

In this article, I am going to discuss the Controllers in ASP.NET MVC Application. Please read our previous article before proceeding to this article where we discussed the need and use of ASP.NET MVC Folders and Files which are by default created when we create a new ASP.NET MVC 5 application. As part of this article, we are going to discuss the following pointers which are related to MVC Controllers.

  1. What is a Controller in the ASP.NET MVC application?
  2. How to Create a Controller in MVC?
  3. Understanding Controller with multiple Examples.
What is a Controller in an ASP.NET MVC application?

A controller in an ASP.NET MVC Application is a class having a set of public methods. These public methods of the controller class are called action methods or simple actions. These action methods in the ASP.NET MVC application are going to handle the incoming HTTP Requests.

The Controllers in an ASP.NET MVC application logically group similar types of actions together. This grouping of action together allows us to define sets of rules such as routing, caching, and authorization which is going to be applied collectively. Please have a look at the following diagram for a better understanding of the controller.

Controllers in ASP.NET MVC Application

As shown in the above diagram, the Controller is the component that is going to receive the incoming HTTP Request and then process that request. While processing the request, the controller does several things. It works with the model. Then it selects a view and if needed then passes the model object to the view. The view then generates the necessary HTML and the controller then sends the HTML back to the client who initially made the request. So we can consider that the Controller is the heart of the MVC application.

By convention, in ASP.NET MVC, the controller classes should reside in the project’s root level Controllers folder and should be inherited from the System.Web.Mvc.Controller base class.

Let’s understand the Controllers in ASP.NET MVC application with an example.

Creating an Empty ASP.NET MVC application:

Open Visual Studio and select File => New => Project as shown in the image below.

Creating an Empty ASP.NET MVC application

Once you click on the “Project” link a new dialog will pop up. From that New Project window, from the left pane select Web template under the Visual C# which is under the “Installed – Templates” section. From the middle pane select ASP.NET Web Application and give the name of your project as FirstMVCDemo. Finally, click on the OK button as shown in the image below.

Selecting Project Type

Once you click on the OK button, then a new dialog window will open with the name New ASP.NET Web Application for selecting the Project Templates. From this window, we are going to select the Empty project template as we are going to do everything from scratch. Finally, click on the OK button as shown in the below image.

Selecting the Project Templates

Once we click on the OK button, it will take some time to create the project with the empty template with the following default folder structure.

ASP.NET MVC Empty Projecct Folder structure

As you can see in the above image, the project is created with several folders such as Models, Views, Controllers, etc. As the names suggest these folders are going to contain Models, Views, and Controllers respectively. We will discuss Models and Views in our upcoming article and in this article, we are going to focus on the Controllers.

Adding Controller to the Project:

To add a controller to your project follow the below steps

  1. Right Click on the “Controllers” folder
  2. Select Add > Controller
  3. Select MVC 5 Controller – Empty
  4. Click on the ADD button as shown in the image below

Adding MVC 5 Controller

Once you click on the Add button, then a new pop-up window will open where you need to provide a name for your controller. Set the Controller Name as HomeController and click on the Add button as shown in the image below.

Naming Controller in MVC

Once you click on the Add button, then you should have HomeController.cs within the “Controllers” folder as shown in the below image.

Controller Folder

At this point, if you run your application, then you will get the following error.

Error in MVC while Finding the Index View
Fixing the Error:

In order to fix the above error, we need to add a view with the name “Index”. We will discuss views in detail in our next article. So here we will fix the above issue in another way. The following is the function that is auto-generated by the HomeController class.

namespace FirstMVCDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

To fix the issue, modify the return type of the Index() action method from “ActionResult” to “string”. Then return a string such as “Hello MVC 5 Application” as shown below.

namespace FirstMVCDemo.Controllers
{
    public class HomeController : Controller
    {
        public string Index()
        {
            return "Hello MVC 5 Application";
        }
    }
}

With the above changes, run the application and you will see the string as expected in the browser window.

Now change the URL to http://localhost:xxxx/Home/Index

In the URL “Home” is the name of the controller and “Index” is the name of the action method within the HomeController class. So the important point that you need to keep in mind is the incoming URL in an ASP.NET MVC application is mapped to a controller action method as shown in the below image.

incoming URL mapped to controller action method

So the next obvious question that should come to your mind is where this mapping is defined?

Well, the mapping is defined within the RegisterRoutes() method of the RouteConfig class. As we already discussed in our ASP.NET MVC Folder and File Structure article,  all the configuration-related files are stored within the App_Start folder. So you can find this RouteConfig class within the App_Start Folder.

Now open the RouteConfig.cs class file and you will see that the RegisterRoutes() method of the RouteConfig class has got a default route as shown in the below image.

RegisterRoutes() method of the RouteConfig class

In the URL, we have not specified the id value. But still, it working and we got the output as expected. This is because as you can see in the defaults, the id parameter is declared as optional.

Let pass the id value in the URL and see what happens.

http://localhost:xxxx/Home/Index/10

When we navigate to the above URL nothing has happened. Now, change the implementation of the Index() action method of the HomeController class as shown below.

Action Method with Parameters

Now when you navigate to “/Home/Index/10“, then the value 10 is assigned to the id parameter of the Index action method and hence it will display the following message in the browser.

The value of Id = 10

Let change the implementation of the Index action method as shown below to accept the query string parameter.

using System.Web.Mvc;
namespace FirstMVCDemo.Controllers
{
    public class HomeController : Controller
    {
        public string Index(string id, string name)
        {
            return "The value of  Id = " + id + " and Name = " + name;
        }
    }
}

Let us issue a request as shown below using the query string.

http://localhost:xxxx/Home/Index/10?name=James

In the above URL, the value 10 is assigned to the id parameter and the query string name is assigned to the name parameter of the Index action method. So the mapping is now done as shown in the image below.Mapping with Query String in MVC

In MVC, you can also use the “Request.QueryString” to retrieve the query string parameter as shown below.

using System.Web.Mvc;
namespace FirstMVCDemo.Controllers
{
    public class HomeController : Controller
    {
        public string Index(string id, string name)
        {
            return "Id = " + id + " ,Name = " + Request.QueryString["name"];
        }
    }
}
So in short,
  1. A controller in ASP.NET MVC Application is a class that is inherited from System.Web.Mvc.Controller.
  2. The MVC controller is the one that is going to interact with both Models and views.
  3. The controller class contains a set of public methods which are also called the action methods. It is these action methods which is going to handle the incoming HTTP Requests.
  4. In ASP.NET MVC, every controller class name must end with the word “Controller”. For example, the controller for the home page must be HomeController and the controller for a student must be StudentController.
  5. Every controller class must be located in the Controllers folder.

In the next article, I am going to discuss Views in the ASP.NET MVC Application with examples. Here, in this article, I try to explain the Controllers in the ASP.NET MVC application with Examples. I hope this Controllers in ASP.NET MVC Application article will help you with your needs.