Mark Gilbert's Blog

Science and technology, served light and fluffy.

Dude, where’s my QueryString? MVC 2, RedirectToAction, and QueryString

In my most recent MVC 2 project, I was working on a gallery that had many "sub-galleries" – really just filtered versions of the full one.  I didn’t want to show the "full" gallery ever, so I wired up the Index.aspx action to redirect to my "default" sub-gallery.  If the user came in through a URL such as

Then it would take them to the default gallery, pre-filtered, which would have the same endpoint as if the user went here:

The "Index" action in the Gallery controller that handled this redirect originally looked like this:

Function Index() As ActionResult
    Return RedirectToAction("mygallery")
End Function

That worked great – until the requirements changed, that is.  A couple of weeks after I wrote this, we uncovered a need to pass in a custom querystring on the URL.  For example:

What I found is that RedirectToAction wasn’t preserving the querystring value at all.  It wasn’t just that the "ProjectID" value was gone – the parameter didn’t even exist.  Through some tinkering, I found that this URL

was also dropping the querystring (notice the extra slash after Gallery), but this one

was working fine.  The latter made total sense – I was bypassing the RedirectToAction() method by going directly to the MyGallery() method.  I looked for a way to force RedirectToAction to preserve the querystring, but I couldn’t find anything.  So, I altered my tack.  Instead of using RedirectToAction() to go to MyGallery, I simply called the MyGallery() method directly from Index():

Function Index() As ActionResult
    Return MyGallery()
End Function

That worked.  I ended up on the correct view, and the querystring was preserved.

I’ve put together a small MVC 2 solution that illustrates this.  Download the "RedirectToAction Lost Querystring" archive from here:  The Home/Index page has some sample links that take you to Gallery/Index, and illustrate the above.  The solution requires Visual Studio 2010, and uses ASP.NET MVC 2.

August 20, 2011 - Posted by | ASP.NET MVC

Sorry, the comment form is closed at this time.

%d bloggers like this: