【发布时间】:2011-08-06 12:27:37
【问题描述】:
我有以下控制器:
public ActionResult Index(int? categoryId)
{
IList<Item> result = categoryId == null ? _itemsService.GetLast(20) : _itemsService.GetByCategory((int)categoryId);
var viewModel = Mapper.Map<IList<Item>, IList<ItemsIndexViewModel>>(result);
return View(viewModel);
}
可以为空的 categoryId 参数是指子类别的 id。如果没有传递任何内容,则必须显示最后 20 个项目,但如果传递了子类别 id,则应显示该类别中的项目。
但我想要的是:www.myDomain.com/Category/SubCategory(例如:/Electronics/Cell-Phones)
我尝试编写路线是这样的:
routes.MapRoute(
"ItemIndex",
"{category}/{subcategory}",
new {controller = "Item", action = "Index", categoryId = UrlParameter.Optional}
);
但我不知道如何传递类别和子类别的值。
任何帮助将不胜感激:)
更新: 以下是我目前得到的路线定义:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" });
routes.MapRoute(
"ItemDetail",
"Item/Detail/{itemId}",
new { controller = "Item", action = "Detail" }
);
routes.MapRoute(
"ItemIndex",
"Items/{category}/{subcategory}",
new { controller = "Item", action = "Index", subcategory = UrlParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
这是我希望将路由映射到的控制器:
public ActionResult Index(string category, string subcategory)
{
// IList<Item> result = string.IsNullOrEmpty(subcategory) ? _itemsService.GetLast(20) : _itemsService.GetByCategory(subcategory);
IList<Item> result;
if (string.IsNullOrEmpty(subcategory))
{
if (string.IsNullOrEmpty(category))
{
result = _itemsService.GetLast(20);
}
else
{
result = _categoryService.GetItemsInTopLevel(category);
}
} else
{
result = _itemsService.GetByCategory(subcategory);
}
var viewModel = Mapper.Map<IList<Item>, IList<ItemsIndexViewModel>>(result);
return View(viewModel);
}
这就是我从视图中调用它的方式:
@model IList<Sharwe.MVC.Models.ParentCategory>
<div id="sharwe-categories">
<ul class="menu menu-vertical menu-accordion">
@foreach(var topLevel in Model)
{
<li class="topLevel">
<h3>
@Html.ActionLink(topLevel.Name, "Index", "Item", new { category = topLevel.Name }, new {@class = "main"} )
<a href="#" class="drop-down"></a>
</h3>
<ul>
@foreach (var childCategory in topLevel.Children)
{
<li>@Html.ActionLink(childCategory.Name, "Index", "Item", new RouteValueDictionary{ { "category" , topLevel.Name }, { "subcategory" , childCategory.Name }})</li>
}
</ul>
</li>
}
</ul>
</div>
当我点击顶级类别时,它工作得非常好。但是单击子类别不起作用。它实际上重定向到http://localhost/?Length=4。我不知道这是从哪里来的。
【问题讨论】:
-
你不认为你的路线也会匹配 Home/create url 或者我错过了什么吗?
-
@Muhammad Adeel Zahid:实际上我认为确实如此。现在,我正在调试,我注意到 Home/Index 立即被触发......为什么会发生这种情况,我该如何防止它?
-
您可能还必须使用一些路由约束。使路由定义类似于
category/{category}/{subcategory}通常更容易,因此限制它会容易得多。
标签: asp.net-mvc asp.net-mvc-3 routing asp.net-mvc-routing