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

ASP.NET MVC - Controller Level Default Action

, 5 Dec 2012 MIT
Rate this:
Please Sign up or sign in to vote.
Change default action at individual controller level in ASP.NET MVC.

This article describes changing the default action at individual controller level, irrespective of the global default action which is defined in the global.asax file.

Implement Action Filter

Implement action filter that will be executed by the ASP.NET MVC infrastructure. Add the below class in your ASP.NET MVC project. And then you can set the attribute to the controller where you wish to set the default action.

[AttributeUsage(AttributeTargets.Class)]
public class DefaultActionAttribute : ActionFilterAttribute
{
    private string _defaultActionName;
    private string _changeTo;

    public DefaultActionAttribute(string changeTo, string defaultActionName= "Index")
    {
        _defaultActionName = defaultActionName;
        _changeTo = changeTo;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string currentAction = filterContext.RequestContext.RouteData.Values["action"].ToString();
        if (string.Compare(_defaultActionName, currentAction, true) == 0)
        {
            filterContext.RequestContext.RouteData.Values["action"] = _changeTo;
        }
        base.OnActionExecuting(filterContext);
    }
}

Example

Now you can set the attribute to the controller where you wish to change the default action.

[DefaultAction("About")]
//Set "About" action as a default action for this controller.
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
        return View();
    }
    public ActionResult About()
    {
        ViewBag.Message = "Your quintessential app description page.";
        return View();
    }
}

License

This article, along with any associated source code and files, is licensed under The MIT License

Share

About the Author

Rajesh Jinaga
Technical Lead
India India
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinmemberS. M. Ahasan Habib12-Feb-13 7:08 
GeneralNice tip! PinmemberMichel Wilker16-Dec-12 0:55 

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 | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 5 Dec 2012
Article Copyright 2012 by Rajesh Jinaga
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid