我使用 NerdDinner 教程作为基础,在 MVC 3 中创建了一个系统。我不确定我是否完全理解路由。
一切正常,直到我向现有的分页助手添加了一个排序。
这里是global.asax.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"UpcomingKeyDates", // Route name
"KeyDates.mvc/{sortBy}/Page/{page}", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}.mvc/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", sortBy = "EventDate" } // Parameter defaults
);
routes.MapRoute(
"Root", // Route name
"", // URL with parameters
new { controller = "Home", action = "Index", sortBy = "EventDate" } // Parameter defaults
);
}
当您第一次导航到页面时,我想默认列表按事件日期升序排序(效果很好)。排序和分页也很好用。但是,当我使用此链接时...
<%: Html.ActionLink("Create New", "Create", "Home") %>
该链接仅指向同一页面。我是否需要添加新路线或修改现有路线?非常感谢任何帮助。
谢谢。
最佳答案
默认路由应该始终出现在最后并且是包罗万象的路由。它会自动捕获相当于 http://yourdomain.com/
默认路由应始终具有以下格式
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "foo", action = "bar", id=UrlParameter.Optional }
);
此外,如果页面将是一个数字,您可以使用正则表达式对其进行约束(见下文)。
简而言之,将您的 Global.asax
更改为如下所示:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"UpcomingKeyDates", // Route name
"KeyDates.mvc/{sortBy}/Page/{page}", // URL with parameters
new { controller = "Home", action = "Index" }, // Parameter defaults
new { page = @"\d+" } // Note I have constrained the page so it has to be an integer...
);
routes.MapRoute(
"MyDefaultRoute", // Your special default which inserts .mvc into every route
"{controller}.mvc/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id=UrlParameter.Optional, sortBy = "EventDate" } // Parameter defaults
);
routes.MapRoute(
"Default", // Real default route. Matches any other route not already matched, including ""
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id=UrlParameter.Optional, sortBy = "EventDate" } // Parameter defaults
);
}
关于c# - ASP.NET MVC 3 - 难以理解路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8847957/