Search code examples
asp.net-mvcasp.net-mvc-routingmvcsitemapprovider

Route parameters not getting preserved [Mvc SiteMap Provider]


I have a Team table, and a Player table, with TeamId as the foreign key.

I need to do CRUD operations on players, for which I have a PlayerController. The Index methods takes teamId as parameter, and shows all players in that team. The Add method also takes teamId as parameter, and adds a player to that team. The Edit method takes playerId as parameter, and edits the corresponding player.

Now, I am using Mvc SiteMap Provider to create menus and breadcrumbs in my project. Showing only the relevant attributes, a part of my sitemap looks as follows:

<mvcSiteMapNode title="Player List" preservedRouteParameters="teamId">
    <mvcSiteMapNode title="Add Player" preservedRouteParameters="teamId"></mvcSiteMapNode>
    <mvcSiteMapNode title="Edit Player" preservedRouteParameters="playerId"></mvcSiteMapNode>
</mvcSiteMapNode>

The problem is that when I navigate to Add Player from Player List, I can get back to Player List page by clicking on the link in the breadcrumb. But when I try going back to the Player List page from the Edit Player page, there is an error, because the URL created by the breadcrumb does not include the teamId parameter.

So basically the teamId parameter for Player List is preserved when I go to Add Player, but not when I go to Edit Player.

Why is it so? Is there a way to fix this?


Solution

  • The reason for this is because preservedRouteParameters only knows about the values in the current request. When navigating to the Edit Player link, there is no teamId in the request so the Player List link won't have a value for teamId to make a copy of.

    You can fix this by adding the teamId to the Edit Player node.

    <mvcSiteMapNode title="Player List" preservedRouteParameters="teamId">
        <mvcSiteMapNode title="Add Player" preservedRouteParameters="teamId"></mvcSiteMapNode>
        <mvcSiteMapNode title="Edit Player" preservedRouteParameters="playerId,teamId"></mvcSiteMapNode>
    </mvcSiteMapNode>
    

    And to add the teamId to the associated route, ActionLinks, RouteLinks, etc. so it will be included in the request every time Edit Player is navigated to.

    Note that it is important to make the teamId reference the same entity in each node with the same common ancestry.