Skip to main content

ASP.NET MVC Controller


ASP.NET MVC Controller Explained


In this article, Csharp Naija will introduce you to ASP.NET MVC controllers. You will learn how to create new controllers and return different types of action results.
This article explores the topic of ASP.NET MVC controllers, controller actions, and action results. The article is meant to teach you how controllers are used to control the way a visitor interacts with an ASP.NET MVC Applications.

What are Controllers?

MVC controllers are the C part of MVC, responsible for responding to requests made against an ASP.NET MVC Application. Each browser request is mapped to a particular controller. We will be using the controllers created in our previous article EntityFramework Explained. For example, imagine that you enter the following URL into the address bar of your browser:
http://localhost/Sample/Index/3

In this case, a controller named SampleController is invoked. The SampleController is responsible for generating the response to the browser request. For example, the controller might return a particular view back to the browser or the controller might redirect the user to another controller.

The listing below contains a simple controller named SampleController.
Controllers\SampleController.cs
using System.Web.Mvc;

namespace DatabaseFirstApproach.Controllers
{
    public class SampleController : Controller
    {
        // GET: Sample
        public ActionResult Index()
        {
            return View();
        }

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

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

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

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

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

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

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

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

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

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

As you can see from above code, a controller is just a class (C# class). A controller is a class that derives from the base System.Web.Mvc class. Because a controller inherits from this base class, a controller inherits several useful methods for free (these methods treated later in this article).

Controller Actions


A controller exposes controller actions. An action is a method on a controller that gets called when you enter a particular URL in your browser address bar. For example, imagine that you make a request for the following URL:

http://localhost/Sample/Index/3

In this case, the Index() method is called on the SampleController class. The Index() method is an example of a controller action.

A controller action must be a public method of a controller class. C# methods, by default, are private methods. Realize that any public method that you add to a controller class is exposed as a controller action automatically (You must be careful about this since a controller action can be invoked by anyone in the universe simply by typing the right URL into a browser address bar).

There are some additional requirements that must be satisfied by a controller action. A method used as a controller action cannot be overloaded. Furthermore, a controller action cannot be a static method. Other than that, you can use just about any method as a controller action.

Note:

Method of Overloading

Method Overloading is the common way of implementing polymorphism. It is the ability to redefine a function in more than one form. A user can implement function overloading by defining two or more functions in a class sharing the same name. C# can distinguish the methods with different method signatures. i.e. the methods can have the same name but with different parameters list (i.e. the number of the parameters, order of the parameters, and data types of the parameters) within the same class. Read more about Method Overloading here

Static Method

C# supports two types of class methods, static methods, and non-static methods. Any normal method is a non-static method. 
A static method in C# is a method that keeps only one copy of the method at the Type level, not the object level. That means, all instances of the class share the same copy of the method and its data. The last updated value of the method is shared among all objects of that Type. 

Static methods are called by using the class name, not the instance of the class. Read more about Static Methods here

Action Results

A controller action returns something called an action result. An action result is what a controller action returns in response to a browser request.



The ASP.NET MVC framework supports several types of action results including:
1.     ViewResult - Represents HTML and markup.
2.     EmptyResult - Represents no result.
3.     RedirectResult - Represents a redirection to a new URL.
4.     JsonResult - Represents a JavaScript Object Notation result that can be used in an AJAX application.
5.     JavaScriptResult - Represents a JavaScript script.
6.     ContentResult - Represents a text result.
7.     FileContentResult - Represents a downloadable file (with the binary content).
8.     FilePathResult - Represents a downloadable file (with a path).
9.     FileStreamResult - Represents a downloadable file (with a file stream).

All of these action results inherit from the base ActionResult class.

In most cases, a controller action returns a ViewResult. For example, the Index controller action in Listing below returns a ViewResult.

Controllers\SampleController.cs
// GET: Sample
        public ActionResult Index()
        {
            return View();
        }

When an action returns a ViewResult, HTML is returned to the browser. The Index() method in Listing above returns a view named Index to the browser.

Notice that the Index() action in Listing above does not return a ViewResult(). Instead, the View() method of the Controller base class is called. Normally, you do not return an action result directly. Instead, you call one of the following methods of the Controller base class:

1.     View - Returns a ViewResult action result.
2.     Redirect - Returns a RedirectResult action result.
3.     RedirectToAction - Returns a RedirectToRouteResult action result.
4.     RedirectToRoute - Returns a RedirectToRouteResult action result.
5.     Json - Returns a JsonResult action result.
6.     JavaScriptResult - Returns a JavaScriptResult.
7.     Content - Returns a ContentResult action result.
8.     File - Returns a FileContentResult, FilePathResult, or FileStreamResult depending on the parameters passed to the method.

So, if you want to return a View to the browser, you call the View() method. If you want to redirect the user from one controller action to another, you call the RedirectToAction() method. 

For example, the Create() action in Listing below either displays a view or redirects the user to the Index() action depending on whether the form is fully filled.

employees/Create from employeesController.cs
// POST: employees/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,FirrstName,MiddleName,LastName,Address,PhoneNumber,DateOfBirth,DepartmentId")] employee employee)
        {
            if (ModelState.IsValid)
            {
                db.employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.DepartmentId = new SelectList(db.departments, "Id", "DeptName", employee.DepartmentId);
            return View(employee);
        }

The ContentResult action result is special. You can use the ContentResult action result to return an action result as plain text. For example, the Details() method in Listing below returns a message as plain text and not as HTML.

Controllers\SampleController.cs Listing

// GET: Sample/Details/5
        public ActionResult Details(int id)
        {
            return Content("Hello Csharp Naija");
        }

When the SampleController.Details() action is invoked, a view is not returned. Instead, the raw text "Hello Csharp Naija" is returned to the browser.

If a controller action returns a result that is not an action result - for example, a date or an integer - then the result is wrapped in a ContentResult automatically. 

For example, when the NoActionResult() action of the SampleController in Listing below is invoked, the date is returned as a ContentResult automatically.

SampleController.cs Listing

 public DateTime NonActionResult()
        {
            return DateTime.Now;
        }

The NonActionResult() action in Listing above returns a DateTime object. The ASP.NET MVC framework converts the DateTime object to a string and wraps the DateTime value in a ContentResult automatically. The browser receives the date and time as plain text.

You can now see that controllers and controller actions play major roles in the request and response aspect of ASP.NET MVC Web Applications. This article is referenced from Microsoft Documentation by StephenWalther.

Comments

Popular posts from this blog

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...