ASP.NET MVC 3 Redirect Query String with id

This tip is mostly because I’ve run into this issue a few times and keep forgetting what I did. The tip concerns an ASP.NET MVC 3 Query string property for redirect using the key ‘id’ when you have a route defined that uses ‘id’ as such:

"{controller}/{action}/{id}"

And you want to redirect to: mywebsite.com/controller/action?id=SomeValue

You also want to keep that id query string because it is a string value that can be a GUID or some string or even an integer. Yes I realize this is bad design but I was working on something out of my control.

The way to accomplish this is to use this:

Redirect(Url.Action("Action", "Controller") + "?id=" + id);

Instead of:

return RedirectToAction(“Action”, “Controller”, new { id = idvalue });

When you use RedirectToAction, it will format your url and remove the querystring which you want to keep. By using Redirect and forging the query string yourself, you get to keep the ‘?id’ part in the URL.

Advertisement
Tagged , , ,

3 thoughts on “ASP.NET MVC 3 Redirect Query String with id

  1. Mac says:

    Thanks! I was stuck in the same issue, that really helped.

  2. Dago Mx says:

    Thanks! Very useful!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: