2

I have a Listings controller with an Index action that takes an optional category parameter...

public ActionResult Index(string category) { ... }

I have the standard default route in global.asax...

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

If I call...

@Html.ActionLink("Show All Listings", "Index", "Listings") 

...from within a view (even a view for the same action with a category specified) I get a link to "/Listings".

If I call...

@Html.ActionLink("Show Listings for Category A", "Index", "Listings", new { category = "CategoryA" }, null)

...I get a link to "/Listings?category=CategoryA". All good so far.

So what I wanted to achieve is to create a custom route for when the category is specified. To do this I added a custom route to global.asax just before the above route as follows:

routes.MapRoute(
    "ListingCategories",
    "listings/category/{category}",
    new { controller = "Listings", action = "Index" }
);

Now if I call...

@Html.ActionLink("Show Listings for Category A", "Index", "Listings", new { category = "CategoryA" }, null)

...I get a nice link "/Listings/Category/CategoryA"

But here's the problem. If I call...

@Html.ActionLink("Show All Listings", "Index", "Listings")

...from the view for the above action with the category = "CategoryA", the link that is generated is "/Listings/Category/CategoryA" instead of just "/Listings". But when I make the same call from any other view the link is generated fine as "/Listings".

I've tried calling...

@Html.ActionLink("Show All Listings", "Index", "Listings", new { category = "" }, null)

...and it still generates the link as "/Listings/Category/CategoryA" when called from the view for the action that had category = "CategoryA". However if I set category to any non empty string, then it generates the link to the correct category (whatever I specify).

Is this expected behavior?

1 Answer 1

2

Modify your route so that category is optional

routes.MapRoute(
    "ListingCategories",
    "listings/category/{category}",
    new { controller = "Listings", action = "Index", category = UrlParameter.Optional }
);

Your previous route makes the category required so the ActionLink doesn't match that route but instead matches another route like the Default one.

1
  • Yes, and in addition to this I added a route for when no category is specified for just the /listings url
    – Michael
    Jul 24, 2011 at 12:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.