Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Actions in ASP.NET MVC 3

0.00/5 (No votes)
12 May 2011 2  
A deeper look into different Actions, Action filters, and selectors used inside a Controller.

Introduction

ASP.NET MVC provides a new way of creating web applications which are more extensible and testable. We discussed about ASP.NET MVC in Introduction to ASP.NET MVC 3. Also, we discussed about Routers and Controllers in ASP.NET MVC 3. Here, we will take a deeper look into the different Actions, Action filters, and selectors used inside a Controller.

Action Result

By default, the Controller actions will return the ActionResult object. We can return various types of results as ActionResult, which will decide how the output needs to render on the browser.

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

Sample Controller

For our sample, we will use the following SampleController in addition to the default HomeController and AccountController.

public class SampleController : Controller
{
    //
    // GET: /Sample/

    public ActionResult Index()
    {
        return Content("Hello from Index action in Sample Controller");
    }
    public ActionResult Verify(string username = "all")
    {
        return Content("Hello from Verify action in Sample Controller");
    }

}

Here, we will discuss about some of the ActionResults available as part of ASP.NET MVC 3.

1. Content

When we need to return any text from a Controller action, we will use the Content type.

public ActionResult Index()
{
    return Content("Hello from Home Controller");
}

2. RedirectToAction

Depending on the input values, we can redirect to another Action. For redirecting to another Action, we will use the RedirectToAction type.

public ActionResult Index()
{
    // Redirect to Verify action inside the Sample Controller
    return RedirectToAction("Verify", "Sample");
}

3. RedirectToRoute

When we need to redirect to a route defined in Global.asax, we will use the RedirectToRoute object.

As part of our sample application, we have a custom route defined with the name “sample”. This will route to the Index action inside the Sample Controller. For more on Custom routes, please refer to Controllers and Routers in ASP.NET MVC 3.

public ActionResult Index()
{
    return RedirectToRoute("sample");
}

4. File

File is used to return the content of a file to the browser. For our sample, I am returning the web.config to the browser.

public ActionResult Index()
{
    return File("Web.config", "text/html");
}

5. JSON

We can render the text to the result page or can send it as a file to the client using JSON notation.

public ActionResult Index()
{
    return Json("hello from JSON","text/html", JsonRequestBehavior.AllowGet);
}

As we specified the type of the content, it will render to the browser as shown below:

public ActionResult Index()
{
    return Json("hello from JSON", JsonRequestBehavior.AllowGet);
}

If there is no content type specified, it will download the content as a file.

Action Filters

There are a set of Action filters available with ASP.NET MVC 3 to filter actions. Action filters are defined as attributes and applied to an Action or controller.

1. Authorize

Authorize filters ensure that the corresponding Action will be called by an authorized user only. If the user is not authorized, he will be redirected to the login page.

[Authorize]
public ActionResult About()
{
    return View();
}

If the user is not authorized and invoke the About action, then he will redirected to the log on page.

If we need the filter at the controller level, then we can add the filter to the controller class itself.

[Authorize]
public class SampleController : Controller
{
    ……………………………………………
}

2. HandleError

HandleError will handle the various exceptions thrown by the application and display user friendly message to the user. By default, this filter is registered in Global.asax.

Note: If any of the Action filters are added to the filter collection in Global.asax, then the scope of the filter is the application.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
}

For verifying a filter, let us enable a custom error in web.config:

<customErrors mode="On"/>

Now throw an exception from the Home Controller:

public ActionResult Index()
{
    throw new Exception("Verify the HandleError filter");
    ViewBag.Message = "Welcome to ASP.NET MVC!";
    return View();
}

Now run the application and observe the custom error message:

This View is defined under Shared Views. We can change the error message using the Error.cshtml file.

Now, let us remove the filter from Global.asax and verify our application. We will receive the following server error:

Now, let us update the CustomError tag to RemoteOnly and verify our application. Now we can see this error message thrown by the application:

We can specify the HandleError filter for an Action or a controller.

ASP.NET MVC defines Action filters like OutputCache, ValidateInput, etc., as part of ASP.NET MVC 3, which we will discuss later.

Action Selectors

ASP.NET MVC 3 defines a set of Action selectors which determine the selection of an Action. One of them is ActionName, used for defining an alias for an Action. When we define an alias for an Action, the Action will be invoked using only the alias; not with the Action name.

[ActionName("NewAbout")]
public ActionResult About()
{
    return Content("Hello from New About");
}

ASP.NET has more Action selectors like HTTPPost and HTTPGet, which we will discuss later.

Conclusion

Here we had a quick discussion of the various Action result options and Action filters. We will discuss more about Views, Styles, etc., in the next article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here