Brandon Linton
Brandon Linton

Reputation: 4411

Can I default the action name to the controller value in a route in ASP.NET MVC?

I'm using ASP.NET MVC3 and areas...I'd like to have a routing structure that's basically {area}/{controller}/{id}, and make the action equal to the {controller} value. I'd like to do this to emulate the action controller pattern described here, but using MVC3 out of the box.

Basically, it would be great if this works (but it doesn't):

context.MapRoute(
                "Request_Default",
                "Request/{controller}/{id}",
                new { action = "{controller}", id = UrlParameter.Optional }
            );

Upvotes: 0

Views: 612

Answers (1)

Lukáš Novotný
Lukáš Novotný

Reputation: 9052

You can write own Route that will do it or simply put something like this in global.asax:

protected void Application_AcquireRequestState()
{
    var handler = Context.Handler as MvcHandler;

    if (handler == null)
        return;

    var routeData = handler.RequestContext.RouteData;

    var action = routeData.Values["action"];
    if (action == null)
        routeData.Values["action"] = routeData.GetRequiredString("controller");
}

and map route like this:

context.MapRoute(
    "Request_Default",
    "Request/{controller}/{id}",
    new { id = UrlParameter.Optional }
);

Upvotes: 2

Related Questions