ASP.NET MVC Controllers

Controllers are essentially the centerpiece of your application ASP.NET MVC. This is the first recipient that interacts with the incoming HTTP request. So the controller decides which model will be selected, and then it takes data from the model and passes it to the appropriate view after that view is rendered. In fact, controllers control the entire flow of the application, accepting input and providing the correct output.

Controllers are C # classes inherited from System. Web. Mvc.Controller, which is the base class of the built-in controller. Each public method in the controller is called an action method, meaning you can call it from the Internet via some URL to perform the action.

The MVC convention is to put the controllers in the “Controllers” folder created by Visual Studio when you set up the project.

Let’s look at a simple Controller example by creating a new project ASP.Net MVC.

Step 1-Open Visual Studio and select the menu item “File” → ” New ” → “Project”.

A new project dialog box opens.

Step 2-In the left pane, select Templates → Visual C # → The Internet.

Step 3-In the middle panel, select the Web application ASP.NET.

Step 4-Enter the project name ” MVCControllerDemo “in the Name field and click OK to continue. You will see the following dialog box asking you to set the initial content for the project ASP.NET.

Step 5. To simplify the task, select the “Clear” option and check the MVC box under “Add folders and main links for” and click OK.

This will create a basic MVC project with minimal predefined content.

After creating a project in Visual Studio, you will see several files and folders displayed in the Solution Explorer window.

Since we created the project ASP.Net MVC from an empty project template, at the moment the application does not contain anything to run.

Step 6. Add EmployeeController by right-clicking the Controllers folder in the Solution Explorer. Select Add → The controller.

The Add Scaffold dialog box appears.

Step 7-Select MVC 5 Controller-Empty option and click”Add”.

The Add Controller dialog box opens.

Step 8-Set the name EmployeeController and click”Add”.

You will see the new C # file EmployeeController. cs in the Controllers folder, which is also open for editing in Visual Studio.

Now in this app, we will add a custom route for the Employee controller with the default route.

Step 1-Go to the “RouteConfig.cs” file in the “App_Start” folder and add the following route.

<!-- wp:code -->
<pre class="wp-block-code"><code></code></pre>
<!-- /wp:code -->

The full implementation of the RouteConfig.cs file is shown below.

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 comes in and searches for an employee by specifying the URL ” Employee / Mark”. In this case, Mark will be treated as a parameter name, not as an action method. So in this scenario, our default route will not work significantly.

To get the incoming value from the browser when passing a parameter, the MVC Framework provides an easy way to solve this problem. This is done using a 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 the action method, the MVC environment will look for the value corresponding to the parameter name. It will use all possible combinations to find out the value of the parameter. It will search the route data, query string, and so on.

Hence, if you request / Employee / Mark “, then the MVC framework will decide that I need a parameter with ” userInput “, and then Mark will be selected from the URL, and it will be automatically passed.

Server. HtmlEncode simply converts any kind of malicious script to 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 screenshot above, Mark is selected from the URL.

Leave a Reply

Your email address will not be published.

You May Also Like