views:

3770

answers:

4

When you call RedirectToAction within a Controller, it automatically redirects using an HTTP GET. How do I explicitly tell it to use an HTTP POST?

I have an Action that accepts both GET and POST requests, and I want to be able to RedirectToAction using a POST and send it some values.

Like this:

this.RedirectToAction("actionname", new RouteValueDictionary(new { someValue = 2, anotherValue = "text" }));

I want the someValue and anotherValue values to be sent using an HTTP POST instead of a GET. Does anyone know how to do this?

+17  A: 

HTTP doesn't support redirection to a page using POST. When you redirect somewhere, the HTTP "Location" header tells the browser where to go, and the browser makes a GET request for that page. You'll probably have to just write the code for your page to accept GET requests as well as POST requests.

Eli Courtwright
A: 

Here's a question that is similar (on the same topic), but different than this one. Anyway, it still may be of interest to those interested in this question:

http://stackoverflow.com/questions/1936/how-to-redirecttoaction-in-aspnet-mvc-preview-4-without-losing-request-data

Chris Pietschmann
+2  A: 

For your particular example, I would just do this, since you obviously don't care about actually having the browser get the redirect anyway (by virtue of accepting the answer you have already accepted):

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index() {
   // obviously these values might come from somewhere non-trivial
   return Index(2, "text");
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int someValue, string anotherValue) {
   // would probably do something non-trivial here with the param values
   return View();
}

That works easily and there is no funny business really going on - this allows you to maintain the fact that the second one really only accepts HTTP POST requests (except in this instance, which is under your control anyway) and you don't have to use TempData either, which is what the link you posted in your answer is suggesting.

I would love to know what is "wrong" with this, if there is anything. Obviously, if you want to really have sent to the browser a redirect, this isn't going to work, but then you should ask why you would be trying to convert that regardless, since it seems odd to me.

Hope that helps.

Jason Bunting
For the idiots down-voting this: why? I don't have a problem with getting a down-vote per se, but at least tell me why and what is wrong with my answer instead of merely voting it down and leaving no feedback.
Jason Bunting
Who knows why you were downvoted. This is a very useful method.
Peter J
+1  A: 

This is the correct behaviour, this pattern being known as Post/Redirect/Get

http://en.wikipedia.org/wiki/Post/Redirect/Get.

So its okay to make 302 redirection from post which makes a get request.