Reputation: 629
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?
Upvotes: 2
Views: 3011
Reputation: 26689
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.
Upvotes: 2