Chapter 14B. Controllers in MVC

In the ASP.NET MVC framework, a controller is a class that takes a browser request and returns a response. The controller can issue any set of commands to the model and it can render any view back to the browser. In short — it is the boss. In this lesson I explain each of the different types of results that a controller can return, introduce the action filter attributes that can be applied to a controller, and I show you how to create a controller.

This is the code for a sample controller called HomeController:

using System.Web.Mvc;

namespace Lesson14b.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }
    }
}

Warning

All controllers must end with the "Controller" suffix. If you omit the "Controller" suffix you will not be able to invoke the controller.

ACTION METHODS

Each controller contains one or more action methods, which is a special type of method that can pass data to a view. The HomeController includes two action methods: Index and About. In the preceding sample code, both of these action methods return an ActionResult. Action methods all return an instance of a class that is derived from the ActionResult class. Different action result types are provided to handle the different tasks that the action method might want to perform. These are the built-in action result types:

  • ContentResult — This ...

Get ASP.NET 4 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.