Click here to Skip to main content
15,861,172 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET MVC - Controller Level Default Action

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
5 Dec 2012MIT 24K   8   2
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.

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

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


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
S. M. Ahasan Habib12-Feb-13 6:08
professionalS. M. Ahasan Habib12-Feb-13 6:08 
GeneralNice tip! Pin
Michel Wilker15-Dec-12 23:55
Michel Wilker15-Dec-12 23:55 

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.