Kassem
Kassem

Reputation: 8266

How to use route parameters in controller actions?

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.

Upvotes: 0

Views: 5466

Answers (1)

Robert Koritnik
Robert Koritnik

Reputation: 104999

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.

Upvotes: 2

Related Questions