Saturday, August 9, 2008

Posting to WebForm via .NET

Posting data to a form via .NET code is quite simple, thanks to the HttpWebRequest class. You need to follow these steps to accomplish this:

  1. Create an HttpWebRequest object, and set the Method and ContentType properties.
  2. Get the data into a string in the form argument1=value1&argument2=value2. This has to be URL encoded, although you can get away without it if you don't have spaces or any special characters.
  3. Get the RequestStream for the HttpWebRequest object and write the data (parameters to be posted to the form) to it.
  4. Get the HttpWebResponse object for the request.

Here's a code sample:
"using System.Net;", "using System.Web;", "using System.IO;" and "using System.Text;" should be added to the top of your code

WebRequest wReq = HttpWebRequest.Create("http://localhost/Form1.aspx");
wReq.Method = "POST";
wReq.ContentType = "application/x-www-form-urlencoded";
string formData = string.format("name={0}&phone={1}", HttpUtility.UrlEncode("Nitin Reddy"), HttpUtility.UrlEncode("+9715015456"));
byte[] formDataBytes = ASCIIEncoding.ASCII.GetBytes(formData);
wReq.GetRequestStream().Write(formDataBytes, 0, formData.Length);
string returnData = new StreamReader(wReq.GetResponse().GetResponseStream()).ReadToEnd();

No comments: