我在网址生成方面遇到了一个小问题。 ASP.NET MVC下的路由2.我的路由具有可选参数,如果指定了参数,则会正确生成URL。
因此:
routes.MapRoute("Blog", "Articles/{tag}/{page}", new { controller = "Blog", action = "Index" });
使用:
<%: Html.ActionLink(item.Tag, "Index", "Blog", new { tag = item.Tag }, null) %>
正确生成~/Articles/item_tag/1
。该链接有效,我的视图呈现。
我还有其他链接:
<%: Html.ActionLink("See more articles", "Index", "Blog") %>
生成~/Blog
而不是~/Articles
。
如果我添加第二条路线,如:
routes.MapRoute("Blog2", "Articles", new { controller = "Blog", action = "Index" });
我的网址已正确呈现。我无法理解为什么我需要添加第二条路线,因为它似乎非常冗余,因为第一条路线有可选的段。
任何帮助表示感谢。
费边
编辑:添加路线代码。
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Home
routes.MapRoute("Home", "", new { controller = "Home", action = "Index" });
routes.MapRoute("HomeSearch", "Search", new { controller = "Home", action = "Search" });
// Solutions
routes.MapRoute("Solutions", "Solutions", new { controller = "Home", action = "Solutions" });
// Customers
routes.MapRoute("Customers", "Customers", new { controller = "Home", action = "Customers" });
// News
routes.MapRoute("NewsDetails", "News/Details/{id}", new { controller = "News", action = "Details" });
routes.MapRoute("News", "News", new { controller = "News", action = "Index" });
// Articles
routes.MapRoute("BlogDetails", "Articles/Details/{id}", new { controller = "Blog", action = "Details" });
routes.MapRoute("BlogWithTag", "Articles/{tag}/{page}", new { controller = "Blog", action = "Index", tag = "", page = 1 });
routes.MapRoute("Blog", "Articles/{page}", new { controller = "Blog", action = "Index", page = 1 });
// Contact
routes.MapRoute("Contact", "Contact", new { controller = "Contact", action = "Create" });
// Sitemap
routes.MapRoute("Sitemap", "SiteMap", new { controller = "Home", action = "SiteMap" });
答案 0 :(得分:1)
顾名思义,它们是 nonoptional 。因此,如果您未在tag
电话中提供page
和ActionLink()
,则路线不会达到此路线定义。
所以,当您致电Html.ActionLink()
并提供tag
参数但不是page
时,您的示例我猜您必须拥有以{{{}开头的不同路线定义1}},因为您在此处提供的路线无法生成链接:
Article/...
Route没有任何参数类型的知识。这意味着参数/Articles/item_tag/1
值由其他方式提供:
在您的情况下,重要的是,在生成链接时不提供page
和tag
参数值,您的路线定义不会受到影响,而且您的链接也不正确。
为什么你真的得到page
链接?只是因为你最后可能仍然有默认的路由定义:
/Blog
并且由于您确实说控制器是博客并且操作是索引但是没有提供Id,所以它将使用其默认值,这将生成您的默认链接网址正好是{controller}/{action}/{id}
。当你以这种方式看待它时,这是非常明显的不是吗?
答案 1 :(得分:0)
在此:
routes.MapRoute("Blog", "Articles/{tag}/{page}", new { controller = "Blog", action = "Index" });
{tag}
和{page}
令牌不是可选的。它们被硬编码到URI中,并且它们没有默认值。
由于路线中/
和{tag}
之间的{page}
,因此永远不会生成~/Blog
之类的URI。