Controller in MVC Framework

What is Controller?

Controller is a class, derived from the base class System.Web.Mvc.Controller. Controller class contains public methods called Action methods. Controller and its action method handles incoming browser requests, retrieves necessary model data and returns appropriate responses.

Controller is the most important component in MVC application The Controller is responsible for controlling the application logic and acts as the coordinator between the View and the Model.

The Controller receives an input from the users via the View, then processes the user’s data with the help of Model and passes the results back to the View. Every controller class name must end with a word “Controller“. For example, controller for home page must be HomeController and controller for Employ must be EmployController. Also, every controller class must be located in Controller folder of MVC folder structure. In MVC, default controller HomeController and action Index.

How to Add Controller in MVC project

We will explain step to step how to Add a controller in MVC project:-

Step 1 : first of all open the project.

File -> Open -> Project

After open the project you see this screen:-

Step 2 : In Solutions Explorer, Right click in Controllers folder -> Select Add than click on Controller.

After this, this screen will appear:-

Step 3 : Select MVC 5 Controller – Empity and click Add.

After this, this screen will appear:-

Step 4 : Enter the Name of controller and click Add.

We write name HomeController because it is a default Controller name.

This will create HomeController class with Index method in HomeController.cs file under Controllers folder, as shown below.

As you can see above, the HomeController class is derived from Controller class. Every controller in MVC must derived from this abstract Controller class. This base Controller class contains helper methods that can be used for various purposes.

Now, we will return a string from Index action method of above HomeController. Changing the return type of Index method from ActionResult to string and returning string is shown below.

You will learn about ActionResult in the next section.

Then, click F5 to run this controller.

So let’s invoke it from the browser and you will see the following page in the browser.

You may also like...

Leave a Reply

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