MVC 4路由列表页面和详细信息页面

时间:2013-08-12 16:10:59

标签: asp.net-mvc asp.net-mvc-routing

我不得不做一个'黑客'让简单的路由工作,因为我需要。

site.com/Event   <--- controller = Event, action = Index

site.com/Event/{id}   <--- controller = Event, action = Details

site.com/About   <--- using default router settings

当前代码:

routes.MapRoute(
     name: "Event",   // Route name
     url: "Event",    // URL with parameters
     defaults: new { controller = "Event", action = "Index" } // Parameter defaults

 );

routes.MapRoute(
     name: "EventID", // Route name
     url:  "Event/{id}", // URL with parameters
     defaults:  new { controller = "Event", action = "Details", 
                      id = UrlParameter.Optional } // Parameter defaults

);

routes.MapRoute(
     name: "Default",
     url: "{controller}/{action}/{id}",
     defaults: new { controller = "Home", action = "Index", 
                     id = UrlParameter.Optional }
);

有没有更好的方法来编写事件和事件/ {id} ..?

更新 - 工作代码

{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapHttpRoute(
    name: "WebDefaultApi",// renamed WebDefaultApi to avoing unique name conflict in API DefaultApi
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

routes.MapRoute(
    "Details",
    "{controller}/{id}",
    new { controller = "Event", action = "Details" },
    new { id = @"^\d+$" }
);


routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

1 个答案:

答案 0 :(得分:3)

使ID成为必需和整数。此外,由于这是更具体的,请将它放在首位。

routes.MapRoute(
                "Details",
                "{controller}/{id}",
                new { controller = "Event", action = "Details" },
                new { id = @"^\d+$" }
            );

routes.MapRoute(
                "Default",
                "{controller}",
                new { controller = "Home", action = "Index" }
            );

此外,如果您只想将此路由应用于特定控制器,则可以限制:

routes.MapRoute(
                "Details",
                "{controller}/{id}",
                new { controller = "Event", action = "Details" },
                new { id = @"^\d+$", controller= @"(event|news|resources)" }
            );