Click here to Skip to main content
Click here to Skip to main content

Actions in ASP.NET MVC 3

, 12 May 2011
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

ambilykk
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
Follow on   Twitter   LinkedIn

Comments and Discussions

 
Generaleasy to understand PinmemberMember 441147428-Jun-12 0:26 
Generalso useful Pinmembergaobanana10-Jun-12 2:02 
GeneralMy vote of 5 Pinmembermanoj kumar choubey16-May-12 21:21 
QuestionAmazing 3 articles - can't wait for the next: Action selectors like HTTPPost and HTTPGet PinmemberItai Roded17-Apr-12 8:06 
GeneralMy vote of 5 Pinmembersri_mncl2-Apr-12 4:16 
QuestionGood work........ Pinmemberamolpandit12-Mar-12 21:37 
GeneralMy vote of 5 PinmvpShivprasad koirala15-Jun-11 5:00 
GeneralMy vote of 5 PinmemberRhuros15-Jun-11 2:37 
GeneralMy vote of 5 PinmemberMember 201025622-May-11 20:28 
GeneralMy vote of 5 Pinmembersaxenaabhi613-May-11 3:35 
GeneralInformative! Pinmembergokulnathm13-May-11 3:31 
GeneralMy vote of 5 PinmemberRhuros13-May-11 0:32 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 12 May 2011
Article Copyright 2011 by ambilykk
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid