Asp.net-mvc – ASP.net MVC RouteLink and optional routeValues

asp.net-mvcroutelinkroutevalues

I'm trying to figure out how to conditionally set a routeValue which is optional.

I have

<%= Html.RouteLink("<<<","Products",new { page=(Model.Products.PageIndex) }) %>

If a visitor clicks on a "category" I only show products of that category, but if there is no "category" I show all products.

These 2 URLs would be valid:

/Products/Page

/Products/Page?category=cars

The RouteLink is in my pager so I thought I could somehow pass the category parameter in the links in the pager in order to persist the category between pages. However I'm not sure how I handle the case where no category is chosen versus when a category is chosen.

I know I can do this:

<%= Html.RouteLink("<<<","Products",new { page=(Model.Products.PageIndex), category=cars }) %>

But is it possible to handle both cases without creating some awkward if statement?

Best Solution

It's merely an idea but can't you just pass an empty category parameter?

<%= Html.RouteLink("<<<","Products",new { page=(Model.Products.PageIndex), category=(ViewData["CategoryName"]) }) %>

And in your productscontroller where you get the page, just check if it exists or not?

public ActionResult Index(int page, string category)
{
    ViewData["CategoryName"] = category;

    if(!string.IsNullOrEmpty(category)){
        //paging with category
    }else{
        //paging without category
    }
    return View("Create");
}

Or is that what you mean by "awkward if statement"?