Controllers

ASP.NET maps URLs to classes known as controllers.

img placeholder

Controllers process incoming requests, handle interaction, and execute logical action. Controller classes generally call views to generate markup pages. In MVC applications, views only display information, and the controller manages all input and user action such as responding to queries and passing values.

The base class for all controllers is the ControllerBase class. It provides most of the MVC handling by using methods that respond to HTTP requests. Examples of specific controller actions include, but are not limited to the following actions:


  1. HTML and other markup
  2. No result
  3. Redirection
  4. AJAX event
  5. JavaScript event
  6. Text output
  7. File download
  8. File download with a path
  9. File download with a stream

The Controller class inherits from ControllerBase and acts as the default controller implement. This class manages the following steps of processing:

  1. Action method location and validation
  2. Gathering values for action method arguments
  3. Managing action method execution errors
  4. Providing the default WebFormViewEngine class which renders page types (or views)

In a typical usage scenario like entering a URL into a browser and pressing Enter, the controller would invoke a controller related to the page associated with that URL. Then the specific controller would respond to the request by returning the right view or passing control to another controller.

CODING CONTROLLERS

Correct controller syntax requires, among other things, the use of “Controller” as a suffix. Review its syntax below:

public abstract class Controller : ControllerBase, IActionFilter,
    IAuthenticationFilter, IAuthorizationFilter, IDisposable, IExceptionFilter,
    IResultFilter, IAsyncController, IController, IAsyncManagerContainer

Review the following example of a controller for rendering views:

using System;
public class YourController : Controller //Always use the “Controller” suffix { public ActionResult Index() //This is the action method with the name “Index” { return View(); //This serves your view } }

The sequence and design of code should be clear. Note the example above is very general, and within the block containing the returned content, a number of possible options and ways to manipulate the response exist; this also extends to manipulation of the action method. In Part 2, we will take a closer look at controllers.