问题描述
|
我有以下控制器:
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);
}
可为null的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}\",subcategory = UrlParameter.Optional }
);
routes.MapRoute(
\"Default\",// Route name
\"{controller}/{action}/{id}\",// URL with parameters
new { controller = \"Home\",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,new RouteValueDictionary{ { \"category\",topLevel.Name },{ \"subcategory\",childCategory.Name }})</li>
}
</ul>
</li>
}
</ul>
</div>
当我单击顶级类别时,它可以很好地工作。但是,单击子类别不起作用。它实际上重定向到http://localhost/?Length=4
。我不知道这是哪里来的。
解决方法
将它们以控制器动作方法作为参数传递
public ActionResult Index(string category,string subcategory)
{
if (string.IsNullOrEmpty(subcategory))
{
// display top 20
}
else
{
// display subcategory
}
}
字符串已经是引用类型,因此您无需设置其他任何内容。