开发者

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 eq开发者_JAVA百科ual 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 }
            );


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜