[ASP.NET MVC] Controllers – Actions

A controller’s behavior is defined in the methods in a controller class. Each method is exposed on a different URL and is invoked with parameters extracted from the incoming request. Rather than writing output directly in the action method using the “Response” object, you are using the “ActionResult” object.  You can decide what kind of result you want in the controller.

1. Controller Actions

An action is a method on a controller. An action method must satisfy the following requirements:

  • must be public
  • cannot be overloaded
  • cannot be static
  • cannot be an extention method
  • cannot contain ref or out parameters

Each browser request is mapped to a particular controller and the controller’s public method (action method) by Route handlers. The action method might return an output (usuaully a view) back to the browser or redirect the user to another controller.

The default Route mapping is “{controller}/{action}/{id}.” So when a user requests “http://www.mysite.com/Product/Details/30”, a controller named “ProductController” is invoked. The “Details” method in the “ProductController” class is invoked and returns a result back to the user.

You can prevent a public method from being invoked as an action by decorating the method with the [NonAction] attribute.

2. Action Results

An action method returns something, which is called an action result. This is the result of the controller’s processing back to the user.

The ASP.NET MVC supports several types of action results. They are classes which inherit from the “System.Web.Mvc.ActionResult” class.

  • ViewResult – HTML
  • PartialViewResult – HTML
  • EmptyResult – no result
  • JsonResult – a JavaScript Object Notation (used in an AJAX application)
  • JavaScriptResult – a JavaScript script
  • ContentResult – a text
  • FileContentResult – a downloadable file with the binary content
  • FilePathResult – a downloadable file with a path
  • FileStreamResult – a downloadable file with a file stream
  • RedirectResult – a redirection to a new URL.
  • RedirectToRouteResult – a redirection to a new URL by using the specified route values dictionary

If a controller action returns a result that is not an action result then the result is wrapped in a ContentResult automatically.

public string Welcome()
  return "Hello, World";

The string message will be wrapped it into a “ContentResult” object.

3. Returing ActionResult in Controller

Rather than creating a “ActionResult” object directly in the Action method, you need to use helper methods defined in the “Controller” class.

  • protected internal ViewResult View()
  • protected internal PartialViewResult PartialView()
  • protected internal JsonResult Json(Object data)
  • protected internal virtual JavaScriptResult JavaScript(string script)
  • protected internal ContentResult Content(string content)
  • protected internal virtual RedirectResult Redirect(string url)
  • protected internal RedirectToRouteResult RedirectToAction(string actionName)
  • protected internal RedirectToRouteResult RedirectToRoute(Object routeValues)

Each method has its overloaded versions, which get more parameters such as a view name or a model object. The name of a method matches with the return type. Note that these methods are “protected“, therefore they can only be called in the subclasses of the “Controller” class.

4. Returning HTML

The most common response from a controller is “HTML”. When you create a result using the “View()” helper method, data are passed to a corresponding view template (cshtml file in the “Views” folder) and html result is created and sent to the user’s browser.

  • ViewResult View()
  • ViewResult View(Object model)
  • ViewResult View(string viewName)
  • ViewResult View(string viewName, Object model)
  • ViewResult View(string viewName, string layoutName)
  • ViewResult View(string viewName, string layoutName, Object model)
public ActionResult Login()
  Account acc = new Account();
  return View(acc); // to the "Login" view with data
[HttpPost] public ActionResult Login(Account acc)
  // authenicate a user
  return View("LoginResult"); // to a different view

5. Sending a Specific HTTP Status Code

You can send a specific HTTP status code as a result using the “HttpStatusCodeResult” class. The “System.Web.Mvc.HttpStatusCodeResult” derives from “System.Web.Mvc.ActionResult“.

  • public int StatusCode { get; private set; }
  • public string StatusDescription { get; private set; }

You can set these properties in the constructor.

  • public HttpStatusCodeResult(int statusCode)
  • public HttpStatusCodeResult(int statusCode, string statusDescription)
public HttpStatusCodeResult Status()
  return new HttpStatusCodeResult(501, "Server Error");

For your convienence, there are 2 built-in status code result classes: “HttpNotFoundResult” and “HttpUnauthorizedResult

The “System.Web.Mvc.HttpNotFoundResult” class represents the status code 404 and the “System.Web.Mvc.HttpUnauthorizedResult” class represents the code 401. Both classes derive from “HttpStatusCodeResult“.

public HttpStatusCodeResult Status()
  return new HttpUnauthorizedResult("You need to login first.");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s