在《Pro MVC3 Framework》的示例项目中,导航栏中的链接地址形式为: http://xxx/?category=watersport
书中的代码示例:
Nav Controller中的代码示例
public class NavController : Controller { private IProductRepository repository; public NavController(IProductRepository repo) { repository = repo; } public PartialViewResult Menu(string category = null) { ViewBag.SelectedCategory = category; IEnumerable<string> categories = repository.Products.Select(x => x.Category).Distinct().OrderBy(x => x); return PartialView(categories); } }
前台显示页面:Menu.cshtml中的页面
@model IEnumerable<string> @{ Layout = null; } @Html.ActionLink("Home", "List", "Product") @foreach (var link in Model) { @Html.RouteLink(link, new { controller = "Product", action = "List", category=link, page = 1 },new { @class = link == ViewBag.SelectedCategory ? "selected" : null }) }
该示例代码生成的链接如前文所示。
但后续书中的代码中却有展示了类似:http://xxx/watersport 类似的链接地址,如果完全按照书中的方法是得不到该样式的地址的。
于是,我费了好大功夫才找到如何将该样式的地址的方法:
1.首先在RouterCollection中,命名要得到路由地址样式,
1 routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 2 3 routes.MapRoute(null, "", new { controller="Product", action="List",categoray=(string)null,Page=1}); 4 5 routes.MapRoute(null, "Page{page}", new { controller = "Product", action = "List", category = (string)null } 6 , new { page=@"d\+" });//Constraints:page must be numerical 7 8 routes.MapRoute("test", "{Category}", new { controller="Product",action="List",page=1 }); 9 10 routes.MapRoute(null, "{Category}/Page{page}", new { controller="Product",action="List",category=(string)null},new { page = @"\d+" });//Constraints:page must be numerical 11 //routes.MapRoute(null, "{category}/Page{page}", new { controller = "Product", action = "List" }, new { page = @"\d+" }); 12 13 //routes.MapRoute( 14 // "Default", // Route name 15 // "{controller}/{action}/{id}", // URL with parameters 16 // new { controller = "Product", action = "List", id = UrlParameter.Optional } // Parameter defaults 17 //); 18 routes.MapRoute(null, "{controller}/{action}");
这里命名为“test”
2.修改Menu.cshtml的代码:
1 @model IEnumerable<string> 2 @{ 3 Layout = null; 4 } 5 6 @Html.ActionLink("Home", "List", "Product") 7 @foreach (var link in Model) 8 { 9 @Html.RouteLink(link, 10 //new { controller = "Product", action = "List", category=link, page = 1 }, 11 "test", new {category=link}, 12 new { @class = link == ViewBag.SelectedCategory ? "selected" : null }) 13 14 }
这里涉及到了Html.RouterLink()方法的使用,第一个参数是该链接的文字,第二个链接是指定路由表的名称,第三个链接是路由参数,第四个参数是赋值链接的css样式。
修改后,重新编译运行即可得到所要的样式。