tags:

views:

212

answers:

2

If my urls looks like: www.mysite.com/1/home www.mysite.com/1/other-action www.mysite.com/1/another-action/?value=a

how can I switch the 1 parameter while invoking the same action with the same parameters and querystring values?

For example if I'm currently browsing www.mysite.com/1/another-action/?value=a I would like to obtain the necessary links to switch to www.mysite.com/2/another-action/?value=a . . www.mysite.com/x/another-action/?value=a

Url.Action seems not to help...

A: 

The general idea is clone the current RouteValueDictionary, change one value, and then build a new action link based on the new RouteValueDictionary. Here's an example. But you'd probably want to do this in a URL helper, rather than directly in the view:

    <% var foo = new RouteValueDictionary();
       foreach (var value in ViewContext.RouteData.Values)
       {
           foo.Add(value.Key, value.Value);
       }
       foo["id"] = 2;
       var newUrl = Url.Action(foo["action"].ToString(), foo); %>
Craig Stuntz
A: 

Thank you very much. Your solution does not restore the querystring, but I managed to add it by simply checking if Request.QueryString.Count is more than zero and eventually appending it to the Url.Action resulting string. I hoped there were a better solution, but I can live with this :-)

It will restore the query string if you added the query string via routing in the first place. If you did not add the query string via routing, then you will have to re-add it in a way similar to how you added it originally. That information would have been a good thing to include in your question.
Craig Stuntz