Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET
Article

Actions in ASP.NET MVC 3

Rate me:
Please Sign up or sign in to vote.
4.86/5 (54 votes)
12 May 2011CPOL4 min read 163.8K   90   26
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.

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

Sample Controller

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

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

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

Image 1

2. RedirectToAction

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

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

Image 2

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.

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

Image 3

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.

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

Image 4

5. JSON

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

C#
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:

Image 5

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

Image 6

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.

C#
[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.

Image 7

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

C#
[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.

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

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

XML
<customErrors mode="On"/>

Now throw an exception from the Home Controller:

C#
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:

Image 8

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

Image 9

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

Image 10

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

Image 11

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.

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

Image 12

Image 13

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect TCS
India India
I have over 10 years of experience working on Microsoft Technologies. I am carrying the passion on Microsoft technologies specifically on web technologies such as ASP.Net, HTML5, jQuery and Ajax. My interests also include TFS, Azure, Windows 8, Visual Studio 2010. Technology adoption and learning is my key strength and technology sharing is my passion.

Microsoft MVP: Connected Service Developer

Comments and Discussions

 
Questionartical Pin
Member 215792631-Jul-12 22:21
Member 215792631-Jul-12 22:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.