ASP.NET MVC controller



ASP.NET MVC controller

In MVC architecture, incoming requests are handled by controllers. ASP.NET MVC controller is just C# class (usually
inheriting from System.Web.Mvc.Controller, the framework’s built-in controller base class).
Each public method in a controller is known as an action method, meaning you can invoke it from the Web via some URL to
perform an action. The MVC convention is to put controllers in the Controllers folder, which Visual Studio created when
it set up the project.

Adding First Controller

If you were following along you will have HomeController.cs in Controllers folder for the sake of this tutorial, I will assume you don’t have that file created.

To add a controller to the project, right-click the Controllers folder in the Visual Studio Solution Explorer
window and choose Add and then Controller from the pop-up menus.

New MVC Controller

Select the MVC 5 Controller – Empty option

New MVC Controller 2

Write controller name as HomeController as shown in the image below

New MVC Controller Name

The default ASP.NET MVC controller is called Home and controller names have the suffix Controller.

You can see that the class is called HomeController and it is derived from the Controller class, which is found in the System.Web.Mvc namespace.

Let’s modify the Index action to return a string instead of ActionResult

Run the project you can see the string message is returned from the home page

MVC Controller Action Return String

Summary :

In This tutorials we seen how to modify and add new ASP.NET MVC controllers. controllers are just c# classes that handle the incoming requests. They contain action methods which are public function that can be called from URL. In the next tutorial we will see how to alter the routing table and how to send parameters to our action URL.