如何在控制器动作中使用路由参数?

发布于 2024-11-01 06:13:35 字数 3710 浏览 1 评论 0原文

我有以下控制器:

    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。我不知道这是从哪里来的。

I have the following controller:

    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);
    }

The nullable categoryId parameter refers to the id of a sub-category. In case nothing was passed, the last 20 items must be displayed, but if a sub-category id was passed, the items from that category should be displayed.

But what I'm trying to go for is: www.myDomain.com/Category/SubCategory (ex: /Electronics/Cell-Phones)

My attempt at writing a route is this:

        routes.MapRoute(
            "ItemIndex",
            "{category}/{subcategory}",
            new {controller = "Item", action = "Index", categoryId = UrlParameter.Optional}
            );

But I have no idea how to pass the values of the category and subcategory.

Any help would be appreciated :)

UPDATE:
Here are the route definitions I've got so far:

    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
        );

    }

This is my controller I wish to map the route to:

    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);
    }

And here's how I'm calling it from the View:

@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>

When I click on a top level category, it works perfectly fine. But clicking on the sub-categories does not work. It actually redirects to http://localhost/?Length=4. I have no idea where this is coming from.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莳間冲淡了誓言ζ 2024-11-08 06:13:35

将它们作为参数传递到控制器操作方法中

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

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

Pass them in controller action method as parameters

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

Strings are already reference types so you don't have to set anything else.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文