如何在控制器动作中使用路径参数?
|
我有以下控制器:
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}\",
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
。我不知道这是哪里来的。
没有找到相关结果
已邀请:
1 个回复
矾醒忻
字符串已经是引用类型,因此您无需设置其他任何内容。