O'Reilly logo

ASP.NET 4 24-Hour Trainer by Toi B. Wright

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required