Reputation: 3453
I’ve got the following code (from a partial view), which creates a list of links enabling me to filter the items listed within my index page according to the letter they begin with:
@{
string letters = "abcdefghijklmnopqrstuvwxyz";
}
<ul>
<li>@Html.ActionLink("0–9", "Index")</li>
@foreach (char c in letters.ToCharArray()) {
<li>@Html.ActionLink(c.ToString().ToUpper(), "Index", new { letter = c.ToString() })</li>
}
</ul>
The first link in the list is for cases where the items begin with a number. I’ve also got the following routes set up in my Global.asax file:
routes.MapRoute(
"",
"artists",
new { controller = "Artist", action = "Index" }
);
routes.MapRoute(
"",
"artists/{letter}",
new { controller = "Artist", action = "Index" },
new { letter = "[a-z]" }
);
So the paths for the links that the above partial view creates should look something like:
/artists
/artists/a
/artists/b
…
and so on. What I’m getting though is odd in that it’s ignoring the routing and creating links like:
/artists
/artists?letter=a
/artists?letter=b
…
Now, if I swap around the order of the routes, it produces the links as I want them, but then I run into another problem. If I then navigate to /artists/a (or any other letter), the first link in the list picks up the current value of the letter parameter and appends it to the list, so I end up with links like:
/artists/a
/artists/a
/artists/b
…
As you can see, that makes it impossible to get back to the index with no filtering. Any ideas as to how I can either fix the routing so that the links are created correctly without the parameters being passed as a query string, or fix the ActionLink as to not append the current parameter?
Upvotes: 1
Views: 1504
Reputation: 20210
Make only one route and set the {letter}
parameter as optional.
routes.MapRoute(
"artists",
"artists/{letter}",
new { controller = "Artist", action = "Index", letter = UrlParameter.Optional },
new { letter = "[a-z]" }
);
EDIT:
Have a look at this post.
EDIT2:
Another possible solution would be:
routes.MapRoute(
"artists",
"artists/{letter}",
new { controller = "Artist", action = "Index", letter = "0" },
new { letter = "[0a-z]" }
);
@Html.ActionLink("0–9", "Index", new { letter = "0"} );
Upvotes: 1