English 中文(简体)
ASP.NET MVC - Controllers
  • 时间:2024-11-03

ASP.NET MVC - Controllers


Previous Page Next Page  

Controllers are essentially the central unit of your ASP.NET MVC apppcation. 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 controlpng the overall flow of the apppcation 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 pubpc 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 cpck on File → New → Project menu option.

A new Project dialog opens.

Visual Studio Project Menu

Step 2 − From the left pane, select Templates → Visual C# → Web.

Step 3 − In the middle pane, select ASP.NET Web Apppcation.

Step 4 − Enter the project name ‘MVCControllerDemo’ in the Name field and cpck ok to continue. You will see the following dialog, which asks you to set the initial content for the ASP.NET project.

MVCControllerDemo

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 cpck 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 apppcation does not contain anything to run.

Step 6 − Add EmployeeController by right-cpcking on Controllers folder in the solution explorer. Select Add → Controller.

EmployeeController

It will display the Add Scaffold dialog.

EmployeeController Scaffolding Dialog

Step 7 − Select the MVC 5 Controller – Empty option and cpck ‘Add’ button.

The Add Controller dialog will appear.

MVC 5 Controller

Step 8 − Set the name to EmployeeController and cpck ‘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.

Custom Route Employee Controller

Now, in this apppcation 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 {
   pubpc class RouteConfig {
      pubpc 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 pke 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  {
   pubpc class EmployeeController : Controller {
      // GET: Employee
      pubpc 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 mapcious 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.

Localhost Employee Mark

As you can see in the above screenshot, Mark is picked from the URL.

Advertisements