65.9K
CodeProject is changing. Read more.
Home

ASP.NET MVC - Controller Level Default Action

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (3 votes)

Dec 5, 2012

MIT
viewsIcon

24751

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();
    }
}