Controllers are your ASP.NET MVC application’s main unit. This is the first recipient to interact with the incoming HTTP application. The controller therefore decides which model to select and then transfers the data from the model to the respective view after the view is rendered. Actually, the controllers control the overall flow of the application from the input to the correct output.

Controllers are classes of C # inherited from System.Web.Mvc.Controller, which is the base class of the builtin controller. Each public method in a controller is known as an action method, which means that you can invoke it from the Web to perform an action via some URL.

The MVC convention is to place controllers in the controllers directory created by Visual Studio when the project was set up. Let’s look at a simple Controller example by building a new ASP.Net MVC project.

Step 1 ? Open the Visual Studio, then click File and then Project menu. A new project dialog opens thereafter.

ASP.NET MVC ControllersStep 2 ? Select Templates from the left pane and then Visual C # and then Web.

Step 3 ? Select ASP.NET Web Application in the middle panel.

Step 4 ? In the Name field, enter the project name ‘ MVCControllerDemo’ and click OK to proceed. You will see the following dialog asking you to set the initial ASP.NET project content.

ASP.NET MVC ControllersStep 5 ? To keep things simple, select the empty option and select the checkbox MVC in the section ‘Add folders and core references’ and click Ok.

A basic MVC project with minimally predefined content will be created. Once Visual Studio has created the project, you ‘ll see a number of files and folders in the Solution Explorer window.

Since we have created an ASP.Net MVC project from an empty project template, there is currently nothing to run in the application.

Step 6 ? Add EmployeeController to the solution explorer by right clicking the Controllers folder. Choose Add Controller.

ASP.NET MVC Controllers

The Add Scaffold dialog will be displayed.

ASP.NET MVC Controllers

Step 7 ? Choose the MVC 5 Controller–Empty option and then click ‘Add’. Then Add Controller dialog is shown.

ASP.NET MVC ControllersStep 8 ? Set the EmployeeController name and press the Add button. You will see a new C # file in the Controllers folder, EmployeeController.cs, which can also be edited in Visual Studio.

ASP.NET MVC Controllers

Step 1 ? Go to file “RouteConfig.cs” in the folder “App Start” and add the next route.

routes.MapRoute(
               "Employee", "Employee/{name}", new { controller = "Employee", action = "Search",  name = UrlParameter.Optional }
            );

The full implementation of the RouteConfig.cs file is as follows.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MVCControllerDemo
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
               "Employee", "Employee/{name}", new { controller = "Employee", action = "Search",  name = UrlParameter.Optional }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

Consider a scenario in which any user searches for an employee and specifies the “Employee/Mark ” URL. In this case, Mark is treated as a parameter name that does not match the action procedure.

So, our default route will not work significantly in this type of scenario. To get the input value from the browser when the parameter is passed, the MVC framework offers a simple way to deal with this problem. It is by using the action method parameter.

Step 2 ? Use the following code to change the EmployeeController class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCControllerDemo.Controllers
{
    public class EmployeeController : Controller
    {
        // GET: Employee
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Search(string name)
        {
            var input = Server.HtmlEncode(name);
            return Content(input);
        }
    }
}

If you add a parameter to the action method, the MVC framework will search for the value corresponding to the parameter. All possible combination will be applied to determine the parameter value.

It searches in the data route, query string, etc. Therefore, if you request /Employee/Mark” then MVC framework will decide that I need a “UserInput” parameter, and then Mark will be selected from the URL and passed automatically.

Server.HtmlEncode simply converts to plain text any type of malicious script. When the above code is compiled and executed and the URL http:/localhost:2921/Employee/Mark is requested, the following output is obtained.

ASP.NET MVC Controllers

ASP.NET MVC ControllersAs you can see from the screenshot above, Mark & Jade is selected from the URL.