将所选类别从导航栏传递到控制器

时间:2014-12-23 20:39:21

标签: asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing

我有一个侧栏用于产品类别。 我的controller是这样的:

public PartialViewResult Menu(string cateogry = null)
{
    ViewBag.SelectedCategory = cateogry;

    IEnumerable<string> cateogries = repository.Products.Select(x => x.Category).Distinct().OrderBy(x => x);

    return PartialView(cateogries);
}

我的路由就是这样:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(null,
        "",
        new
        {
            controller = "Product",
            action = "List",
            category = (string)null,
            page = 1
        }
    );

    routes.MapRoute(null,
        "Page{page}",
        new { controller = "Product", action = "List", category = (string)null },
        new { page = @"\d+" }
    );

    routes.MapRoute(null,
        "{category}",
        new { controller = "Product", action = "List", page = 1 }
    );

    routes.MapRoute(null,
        "{category}/Page{page}",
        new { controller = "Product", action = "List" },
        new { page = @"\d+" }
    );

    routes.MapRoute(null, "{controller}/{action}");
}

但是,当我点击我的类别按钮时,仍会将类别传递为null,因此它不会突出显示所选的类别按钮。我还缺少什么?

view

@model IEnumerable<string>

@Html.ActionLink("Home", "List", "Product", null, new {@class = "btn btn-block btn-default btn-lg"})

@foreach (var link in Model)
{
    @Html.RouteLink(link, new
    {
        controller = "Product",
        action = "List",
        category = link,
        page = 1
    },
        new
        {
            @class = "btn btn-block btn-default btn-lg" +
            (link == ViewBag.SelectedCategory ? "btn-primary" : "")
        })
}

0 个答案:

没有答案