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 is by default created when we create a new ASP.NET MVC 5 application. 

What is a Controller in ASP.NET MVC application?

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

The Controllers in ASP.NET MVC application logically group similar type 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.

Controllers in ASP.NET MVC Application

As shown in the above diagram, the Controller is the component which 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 by passing the model object which renders the user interface from the model data. The view then generates the necessary HTML and then the controller sends 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 projects root level Controllers folder and should inherit from the System.Web.Mvc.Controller base class.

Let’s understand the Controller 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 which 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 state 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 discuss the Controllers in ASP.NET MVC application.

Adding Controller to the Project:

To add a controller in your project follow the below steps

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

Adding MVC 5 Controller

Once you click on the Add button, then a new pop up 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 the application then you will get the following error.

Error in MVC while Finding the Index ViewFixing 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 with 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 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 obvious question that comes to your mind is where this mapping is defined?

Well, the mapping is defined within the RegisterRoutes() of the RouteConfig class. As we already discussed in our ASP.NET MVC Folder and File Structure article that all the configuration related files are going to be stored within the App_Start project root 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 default the id parameter is declared as optional.

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

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 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 the 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 MVC is a class which is inherited from System.Web.Mvc.Controller.
  2. The MVC controller is the one which is going to interact with both Models and views.
  3. The controller class contains a set of public methods which are also called as the action methods. It is these action methods which is going to handle the incoming URL.
  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.
SUMMARY

In this article, I try to explain the Controllers in ASP.NET MVC application with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *