views:

1717

answers:

2

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?

+1  A: 

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"?

Peter
Thanks for the detailed example. I did not know that if you pass empty or null into the routValues it would not output the value name. Very cool!
metanaito
My pleasure, glad I could help
Peter
+1  A: 

If cars variable is null or empty string, Html.RouteLink method will not add category parameter to URL automatically. You don't need to do extra checking.

Alexander Prokofyev
Thank you. Maybe it's because I'm not used to it or maybe I'm just dumb but slowly I'm starting to understand the conventions of asp.net MVC... although it often seems like 'magic' to me.
metanaito