Axel
Axel

Reputation:

How to self-redirect and changing a parameter in asp.net mvc?

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...

Upvotes: 2

Views: 1260

Answers (2)

Grebets Kostyantyn
Grebets Kostyantyn

Reputation: 343

I would propose small optimization to Craig's answer:

<% var foo = new RouteValueDictionary(ViewContext.RouteData.Values); foo["id"] = 2; var newUrl = Url.Action(foo["action"].ToString(), foo); %>

Upvotes: 0

Craig Stuntz
Craig Stuntz

Reputation: 126547

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); %>

Upvotes: 3

Related Questions