Wednesday, July 28, 2010

ASP.NET Post AND Redirect

Working on a C# ASP.NET application where I needed to post data to another legacy website application that would process the results and allow the user to continue about their business on the "other" website.  The HTTP POST occurs within a button onClick event handler in the code-behind of my application.  Doing an HTTP POST is not all that difficult and there are lots of examples of how to do this, but redirecting the user there at the same time presents a whole new problem in ASP.NET.  This is FAR more difficult than you might guess.  In HTML you just setup the FORM tag to post the data to the "other" site and problem solved, but once you get into the code-behind server-side methodology that ASP.NET uses, you find your back is up against a wall with this one.

Thankfully I found an article on The Code Project written by Samer Abu Rabie that solved my problem completely.  Download the HttpHelper.cs file that is attached to the article, add it to your App_Code directory, and then call it like this:

NameValueCollection data = new NameValueCollection();
data.Add("v1", "val1");
data.Add("v2", "val2");
HttpHelper.RedirectAndPOST(this.Page, "http://DestUrl/Default.aspx", data);