情况如下:areas中有admin和newscontent两个区块,其中new中router设置如下:
public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "NewsContent_default", "NewsContent/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); context.MapRoute( null, "", new { controller = "Newss", action = "List", category = (string)null, page = 1 } ); context.MapRoute( null, "Page{page}", new { controller = "Newss", action = "List", category = (string)null }, new { page = @"\d+" } ); context.MapRoute ( "null", // 路由名称 "{category}", // 带有参数的 URL new { controller = "Newss", action = "List", page = 1 } // 参数默认值 ); context.MapRoute( null, "{category}/Page{page}", new { controller = "Newss", action = "List" }, new { page = @"\d+" } ); }
也就是访问http://domain/category/page 时候是访问了http://domain/Newscontent/Newss/list/category/page
但是在http://domain/Newscontent/Newss/index 导航菜单中用RouterLink只能生成如http://domain/NewsContent/Newss/List?category=3&page=1 的连接
代码如下
<% foreach (var link in Model) { %> <%: Html.RouteLink(link.Text, link.RouteValues, new Dictionary<string, object> { { "class", link.IsSelected ? "selected" : null} })%> <% } %>
RouterValues如下:
RouteValues = new RouteValueDictionary(new
{
controller = "Newss",
action = "List",
category = categoryName,
page = 1
}),
我想生成如http://domain/category/page的连接,需要怎么做?
你把最后两个路由的顺序互换试试。
不是路由的问题,用
<%: Html.RouteLink(link.Text, link.RouteValues, new Dictionary<string, object> {
{ "class", link.IsSelected ? "selected" : null} })%>
生成的连接就是http://domain/NewsContent/Newss/List?category=3&page=1的形式,如果生成http://domain/NewsContent/Newss/List/3/page1这样的也行
我错的,确实是路由的问题,还是对route的原理还有mvc的运行过程理解不透彻,routelink生成链接的时候就已经调用route来生成的。context.MapRoute去匹配的时候是根据参数来匹配,如果把context.MapRoute(
"NewsContent_default",
"NewsContent/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
和context.MapRoute(
"NewsContent_default",
"NewsContent/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
放在前边,尽管后边还有category=3和page=1的参数,但是在第一个规则里边已经可以匹配了。所以后边就显示category=3&page=1的形式
@mzwkkk: 问题解决了就好了
@Html.ActionLink("Admin", "Index", "Meets", new { area = "Admin" }, null)
@Html.ActionLink("Admin", "Index", "Meets", new { area = "" }, null)