Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET MVC - Controller Level Default Action

0.00/5 (No votes)
5 Dec 2012 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here