2

Based on a condition, how do I redirect to another controller and action while carring over any query strings and the location hash that was in the URL. Is there a built in way to do this?

TruMan1
  • 33,665
  • 59
  • 184
  • 335
  • 2
    Does the hash even make it to the server? – spender Jul 09 '12 at 00:44
  • If this is something you do commonly, this solution is nice. http://stackoverflow.com/questions/6203694/asp-net-mvc-pass-current-get-params-with-redirecttoaction . However, this won't handle your hash requirements. I haven't looked into this for awhile, but last I did, there wasn't a way to get the hash on the server. (Without doing something clientside to shove the hash into a querystring param or something similar) Like this. http://stackoverflow.com/questions/317760/how-to-get-url-hash-from-server-side . – Kenneth Ito Jul 09 '12 at 02:53

2 Answers2

3

The browser never sends the hash portion to the server when doing an HTTP request. So you cannot redirect and keep the hash because you don't know the hash, it never reached the server. Some techniques consist into using javascript before invoking the controller action that is supposed to do the redirect and manipulate the url in such a way so that the hash part is sent for example as a query string parameter. So once you invoke this controller action you will be able to generate an url with a hash with the GenerateUrl method:

public ActionResult Blah(string hash)
{
    ... do something

    // Generate the url to redirect to using a hash
    var url = UrlHelper.GenerateUrl(
        null,                             // routeName
        "Foo",                            // actionName
        "Bar",                            // controllerName
        null,                             // protocol
        null,                             // hostName
        hash,                             // fragment
        null,                             // routeValues
        RouteTable.Routes,                // routeCollection
        ControllerContext.RequestContext, // requestContext
        false                             // includeImplicitMvcValues
    );

    return Redirect(url);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

There is the RedirectToAction method, but it generates a 302 to the client, what means that the request will change (and that's not what you want).

Please, take a look at the solution provided at How to simulate Server.Transfer in ASP.NET MVC?, I believe that it may help you, although it's not built in.

Regards

Community
  • 1
  • 1
Andre Calil
  • 7,652
  • 34
  • 41