Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Controllers and Action Methods in ASP.NET MVC Applications

.NET Framework 4

The ASP.NET MVC framework maps URLs to classes that are referred to as controllers. Controllers process incoming requests, handle user input and interactions, and execute appropriate application logic. A controller class typically calls a separate view component to generate the HTML markup for the request.

The base class for all controllers is the ControllerBase class, which provides general MVC handling. The Controller class inherits from ControllerBase and is the default implement of a controller. The Controller class is responsible for the following processing stages:

  • Locating the appropriate action method to call and validating that it can be called.

  • Getting the values to use as the action method's arguments.

  • Handling all errors that might occur during the execution of the action method.

  • Providing the default WebFormViewEngine class for rendering ASP.NET page types (views).

    NoteNote

    To help secure access to controllers and action methods, you can use the AuthorizeAttribute class.

All controller classes must be named by using the "Controller" suffix. The following example shows the sample controller class, which is named HomeController. This controller class contains action methods that render view pages.


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

        return View();
    }

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


In ASP.NET applications that do not use the MVC framework, user interaction is organized around pages, and around raising and handling events from the page and from controls on the page. In contrast, user interaction with ASP.NET MVC applications is organized around controllers and action methods. The controller defines action methods. Controllers can include as many action methods as needed.

Action methods typically have a one-to-one mapping with user interactions. Examples of user interactions include entering a URL into the browser, clicking a link, and submitting a form. Each of these user interactions causes a request to be sent to the server. In each case, the URL of the request includes information that the MVC framework uses to invoke an action method.

When a user enters a URL into the browser, the MVC application uses routing rules that are defined in the Global.asax file to parse the URL and to determine the path of the controller. The controller then determines the appropriate action method to handle the request. By default, the URL of a request is treated as a sub-path that includes the controller name followed by the action name. For example, if a user enters the URL http://contoso.com/MyWebSite/Products/Categories, the sub-path is /Products/Categories. The default routing rule treats "Products" as the prefix name of the controller, which must end with "Controller" (such as ProductsController). It treats "Categories" as the name of the action. Therefore, the routing rule invokes the Categories method of the Products controller in order to process the request. If the URL ends with /Products/Detail/5, the default routing rule treats "Detail" as the name of the action, and the Detail method of the Products controller is invoked to process the request. By default, the value "5" in the URL will be passed to the Detail method as a parameter.

The following example shows a controller class that has a HelloWorld action method.

public class MyController : Controller
{
    public ActionResult HelloWorld()
    {
        ViewData["Message"] = "Hello World!";
        return View();
    }
}

Most action methods return an instance of a class that derives from ActionResult. The ActionResult class is the base for all action results. However, there are different action result types, depending on the task that the action method is performing. For example, the most common action is to call the View method. The View method returns an instance of the ViewResult class, which is derived from ActionResult.

You can create action methods that return an object of any type, such as a string, an integer, or a Boolean value. These return types are wrapped in an appropriate ActionResult type before they are rendered to the response stream.

The following table shows the built-in action result types and the action helper methods that return them.

Action Result

Helper Method

Description

ViewResult

View

Renders a view as a Web page.

PartialViewResult

PartialView

Renders a partial view, which defines a section of a view that can be rendered inside another view.

RedirectResult

Redirect

Redirects to another action method by using its URL.

RedirectToRouteResult

RedirectToAction

RedirectToRoute

Redirects to another action method.

ContentResult

Content

Returns a user-defined content type.

JsonResult

Json

Returns a serialized JSON object.

JavaScriptResult

JavaScript

Returns a script that can be executed on the client.

FileResult

File

Returns binary output to write to the response.

EmptyResult

(None)

Represents a return value that is used if the action method must return a null result (void).

By default, the MVC framework treats all public methods of a controller class as action methods. If your controller class contains a public method and you do not want it to be an action method, you must mark that method with the NonActionAttribute attribute.

The following example shows a method that is marked with the NonAction attribute.

[NonAction]
private void DoSomething()
{
    // Method logic.
}

By default, the values for action method parameters are retrieved from the request's data collection. The data collection includes name/values pairs for form data, query string values, and cookie values.

The controller class locates the action method and determines any parameter values for the action method, based on the RouteData instance and based on the form data. If the parameter value cannot be parsed, and if the type of the parameter is a reference type or a nullable value type, null is passed as the parameter value. Otherwise, an exception is thrown.

There are several ways to access URL parameter values in the action methods of controller classes. The Controller class exposes Request and Response properties that can be accessed in an action method. These properties have the same semantics as the HttpRequest and HttpResponse objects that are already a part of ASP.NET. However, the Request and Response objects of the Controller class accept objects that implement the HttpRequestBase and HttpResponseBase abstract classes instead of being sealed classes. These base classes make it easy to create mock objects, which in turn makes it easy to create unit tests for controller classes.

The following example shows how to use the Request object to retrieve a query-string value named id.

public void Detail()
{
    int id = Convert.ToInt32(Request["id"]);
}

The ASP.NET MVC framework can automatically map URL parameter values to parameter values for action methods. By default, if an action method takes a parameter, the MVC framework examines incoming request data and determines whether the request contains an HTTP request value with the same name. If so, the request value is automatically passed to the action method.

The following example shows a variation of the previous example. In this variation, the id parameter is assumed to map to a request value that is also named id. Because of this automatic mapping, the action method does not have to include code to get a parameter value from the request, and the parameter value is therefore easier to use.

public ResultAction Detail(int id)
{
    ViewData["DetailInfo"] = id;
    return View();
}

You can also embed parameter values as part of the URL instead of as query-string values. For example, instead of using the URL with a query string such as /Products/Detail?id=3, you can use a URL like /Products/Detail/3. The default route-mapping rule has the format /{controller}/{action}/{id}. If there is a URL sub-path after the controller and action names in the URL, it is treated as a parameter named id, and is automatically passed to the action method as a parameter value.

The MVC framework also supports optional arguments for action methods. Optional parameters in the MVC framework are handled by using nullable-type arguments for controller action methods. For example, if a method can take a date as part of the query string but you want to the default to be today's date if the query string parameter is missing, you can use code like that in the following example:

public ActionResult ShowArticles(DateTime? date)
{
    if(!date.HasValue)
    {
        date = DateTime.Now;
    }
    // ...
}

If the request includes a value for the date parameter, that value is passed to the ShowArticles method. If the request does not include a value for this parameter, the argument is null, and the controller can take whatever actions are required in order to handle the missing parameter.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft