Controllers are essentially the central unit of your ASP.NET MVC application. It is the 1st recipient, which interacts with incoming HTTP Request. So, the controller decides which model will be selected, and then it takes the data from the model and passes the same to the respective view, after that view is rendered. Actually, controllers are controlling the overall flow of the application taking the input and rendering the proper output.
Controllers are C# classes inheriting from System.Web.Mvc.Controller, which is the builtin 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 that Visual Studio created when the project was set up.
Let’s take a look at a simple example of Controller by creating a new ASP.Net MVC project.
Step 1 − Open the Visual Studio and click on File → New → Project menu option.
A new Project dialog opens.
Step 2 − From the left pane, select Templates → Visual C# → Web.
Step 3 − In the middle pane, select ASP.NET Web Application.
Step 4 − Enter the project name ‘MVCControllerDemo’ in the Name field and click ok to continue. You will see the following dialog, which asks you to set the initial content for the ASP.NET project.
Step 5 − To keep things simple, select the Empty option and check the MVC checkbox in the ‘Add folders and core references for’ section and click Ok.
It will create a basic MVC project with minimal predefined content.
Once the project is created by Visual Studio you will see a number of files and folders displayed in the Solution Explorer window.
Since we have created ASP.Net MVC project from an empty project template, so at the moment, the application does not contain anything to run.
Step 6 − Add EmployeeController by right-clicking on Controllers folder in the solution explorer. Select Add → Controller.
It will display the Add Scaffold dialog.
Step 7 − Select the MVC 5 Controller – Empty option and click ‘Add’ button.
The Add Controller dialog will appear.
Step 8 − Set the name to EmployeeController and click ‘Add’ button.
You will see a new C# file EmployeeController.cs in the Controllers folder, which is open for editing in Visual Studio as well.
Now, in this application we will add a custom route for Employee controller with the default Route.
Step 1 − Go to “RouteConfig.cs” file under “App_Start” folder and add the following route.
routes.MapRoute( "Employee", "Employee/{name}", new{ controller = "Employee", action = "Search", name = UrlParameter.Optional });
Following is the complete implementation of RouteConfig.cs file.
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 wherein any user comes and searches for an employee, specifying the URL “Employee/Mark”. In this case, Mark will be treated as a parameter name not like Action method. So in this kind of scenario our default route won’t work significantly.
To fetch the incoming value from the browser when the parameter is getting passed, MVC framework provides a simple way to address this problem. It is by using the parameter inside the Action method.
Step 2 − Change the EmployeeController class using the following code.
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 Search(string name){ var input = Server.HtmlEncode(name); return Content(input); } } }
If you add a parameter to an action method, then the MVC framework will look for the value that matches the parameter name. It will apply all the possible combination to find out the parameter value. It will search in the Route data, query string, etc.
Hence, if you request for /Employee/Mark”, then the MVC framework will decide that I need a parameter with “UserInput”, and then Mark will get picked from the URL and that will get automatically passed.
Server.HtmlEncode will simply convert any kind of malicious script in plain text. When the above code is compiled and executed and requests the following URL http://localhost:61465/Employee/Mark, you will get the following output.
As you can see in the above screenshot, Mark is picked from the URL.