【问题标题】:How to use route parameters in controller actions?如何在控制器动作中使用路由参数?
【发布时间】: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


【解决方案1】:

将它们作为参数传递给控制器​​操作方法

public ActionResult Index(string category, string subcategory)
{
    if (string.IsNullOrEmpty(subcategory))
    {
        // display top 20
    }
    else
    {
        // display subcategory
    }
}

字符串已经是引用类型,因此您无需设置任何其他内容。

【讨论】:

  • @Robert Koritnik:有道理!这意味着我应该传递这些参数,而不是使用 Html.ActionLink 传递 Id。介意更新您的答案以显示如何从视图传递参数吗?
  • @Robert Koritnik:这是正确的格式吗:@Html.ActionLink(childCategory.Name, "Index", "Item", { category = topLevel.Name, subcategory = childCategory.Name })
  • @Kassem:当然。这是正确的记法。您始终必须提供路由所需的那些参数,否则路由将无法生成链接 URL,并且下一个将尝试生成它。
  • @Robert Koritnik:它仍然对我不起作用!我将更新我的帖子并向您展示我到目前为止所获得的信息。
  • @Kassem:你试过这个吗:&lt;li&gt;@Html.ActionLink(childCategory.Name, "Index", "Item", new { category = topLevel.Name , subcategory = childCategory.Name }, null)&lt;/li&gt;
猜你喜欢
  • 2020-05-09
  • 2020-02-08
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 2011-12-11
  • 1970-01-01
相关资源
最近更新 更多