在《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 numerical11 //routes.MapRoute(null, "{category}/Page{page}", new { controller = "Product", action = "List" }, new { page = @"\d+" });12 13 //routes.MapRoute(14 // "Default", // Route name15 // "{controller}/{action}/{id}", // URL with parameters16 // new { controller = "Product", action = "List", id = UrlParameter.Optional } // Parameter defaults17 //);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樣式。
修改後,重新編譯運行即可得到所要的樣式。