Controller In ASP.NET MVC 5

Let us learn all about Controllers with examples in ASP.NET MVC 5, via this article.

MVC 5

In this article, you will learn the following points about Controllers in MVC 5.

  • What is Controller in ASP.NET MVC 5?
  • How to create an ASP.NET MVC 5 application using Visual Studio 2017?
  • How to create a Controller in MVC 5?
  • How to call a Controller?
  • How to change the default controller?
  • How does the default controller get executed?
  • The flow of Controller in ASP.NET MVC 5

In the previous article, we got an introduction to ASP.NET MVC. If you are new, visit the following link.

Prerequisites

Introduction

MVC stands for Model, View, and Controller. MVC separates the application into three components Model, View, and Controller. We will learn Controller in detail. A controller is one of the important components of MVC.

What is Controller in ASP.NET MVC 5?

  • A controller can contain an action and non-action method.
  • It is used to handle the user requests coming from the browser.
  • It will check the request from the browser and identify the action method and return the respective view.
  • A controller is inherited from “ControllerBase” class which is inside the “System.Web.MVC” namespace.
  • While creating controller remember it always suffix as “Controller” keyword.
  • Default Controller is “HomeController” and “Index” is view.

Following are the steps to create ASP.NET MVC 5 application using Visual Studio 2017.

Step 1. Open => Visual Studio 2017 and go to File >> New >> Click on Project as follow.

Project

Step 2. Select “ASP.NET Web Application” and provide a meaningful name like “MVCControllerDemo” and Click on “Ok” button.

Web Application

Step 3. Select the “Empty” template and check the “MVC” checkbox from “New Web Application” window as follow.

Empty

Step 4. The default project structure will create as follows.

Project structure

How to create a controller in MVC 5?

The following steps will help you to create a controller in ASP.NET MVC 5.

Step 1. Go to solution explorer Right-click on “Controller” Folder >> Click on Add >> click on “Controller” as follow.

Solution explorer

Step 2. Select “MVC 5 Empty Controller” from the window and click on “Add” button.

Empty Controller

Step 3. Provide a meaningful name like “HomeController” and Click on "Add" button.

HomeController

Sample code of Controller as follows,

using System.Web.Mvc;

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

How to check if the Controller is inherited from “ControllerBase” class which is inside the “System.Web.Mvc” namespace?

Right-click on "Controller" click on “Go to definition” as follow.

Controller

ControllerBase

How to create a controller with read/write action in MVC 5 using the default template?

Step to create a controller with read/write action in MVC 5 as follows,

Step 1. Go to Solution Explorer Right-click on the “Controller” Folder >> Click on Add >> click on “Controller” as follows.

Controller Folder

Step 2. Select "MVC 5 Controller with read/write actions" from the window and click on the “Add” button.

Read/write actions

Step 3. Provide a meaningful name like “ProductController” and Click on the “Add” button as follows.

ProductController

Default code is generated for "MVC 5 Controller with read/write actions" as follows.

using System.Web.Mvc;

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

        // GET: Product/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Product/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Product/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Product/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Product/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Product/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Product/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

How to call the controller in MVC 5?

Open any browser and enter the URL like “DomainName/ControllerName” as follows.

DomainName

How to change the default controller?

Open the Routeconfig.cs file default file as follows.

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

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

Change the controller name to the "Product" controller instead of the “Home” controller inside the Routeconfig file as follows.

Routeconfig file

How does the default controller get executed?

The default controller gets executed based on the configuration setting which is applied in the RouteConfig.cs file. We have provided the “Product” controller as the default controller in the Routeconfig.cs file. After executing the application default “ProductController” gets executed.

The flow of Controller in ASP.NET MVC

Following are diagrams that will help you to understand the flow of the ASP.NET MVC Controller.

Model

As per the above figure, the user enters the URL on the browser, the given request goes to the server, and calls the routing, which will execute the appropriate controller. And based on the request the controller executes the appropriate controller action method. It will pass the request to the model if the model has a database-related operation then it will perform some database-related operation and get back the result to the controller. After it's completed, this controller returns the response to the user.

References

Interview questions for freshers on the controller,

  • What is the controller in ASP.NET MVC/MVC 5?
  • What is the base class of Controller?
  • How to change the default Controller in ASP.NET MVC / MVC 5?
  • How does the default controller get executed in ASP.NET MVC 5?

I hope you understand the concepts of the controller in asp.net MVC 5.

Thanks for reading.


Similar Articles