Tuesday, September 6, 2011

Html.ActionLink() outputting current URL parameters

In my MVC application I was using Html.ActionLink() to generate URLs for the menu items on the site navigation. I had a few menu items like "Locations", "Subscribers", "Categories" and "Deals". The URLs for these items where "http://www.mysite.com/Locations", "http://www.mysite.com/Subscribers", "http://www.mysite.com/Categories" and "http://www.mysite.com/Deals" respectively. The links were generated using the following code:

                <ul id="menu">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("Locations", "Index", "Location")</li>
                    <li>@Html.ActionLink("Subscribers", "Index", "Subscriber")</li>
                    <li>@Html.ActionLink("Categories", "Index", "Category")</li>
                    <li>@Html.ActionLink("Deals", "Index", "Deals")</li>
                </ul>

The URLs for the menu items were generated as expected. The "Subscribers" and "Deals" pages supported pagination meaning, we can pass a page number to the URL like http://www.mysite.com/Subscribers/Page/2 and the page would display a subset of the subscribers data instead of all the subscribers from the database.While testing the page, I noticed that the URLs for the Subscribers and Deals were displayed as "http://www.mysite.com/Categories/Page/2" and "http://www.mysite.com/Deals/Page/2" instead of just "http://www.mysite.com/Categories" and "http://www.mysite.com/Deals" respectively. But I wanted the menu item URL to always point to the Categories and Deals URLs irrespective of the current page parameters. After doing some research I figured out this can be accomplished by passing the "ActionName" parameter as an empty string for the ActionLink(). So here is the updated code.
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("Locations", "Index", "Location")</li>
                    <li>@Html.ActionLink("Subscribers", string.Empty, "Subscriber")</li>
                    <li>@Html.ActionLink("Categories", "Index", "Category")</li>
                    <li>@Html.ActionLink("Deals", string.Empty, "Deals")</li>
                </ul>

So now the URLs in the menu items remain the same irrespective of the current page URL parameters.

No comments: