Published on: 05 Aug, 2013

How to Submit Form using Web Request Object in ASP.Net in ASP.Net C#?

Tumblr Digg Google Plus

This tutorial will show you how you can submit form using WebRequest object in ASP.Net CSharp / C#.

Firstly, you will need to import the following namespaces.

    
//required .net objects
using System.Net;
using System.IO;
using System.Collections;

This method will submit form data using WebRequest object.

    
//A Sample void function to send form data
public void SubmitFormData() {
    // Create web request object
    WebRequest objWebRequest;
        
    // Set url properties
    string url = "http://localhost/sampleform/response.aspx";
    objWebRequest = WebRequest.Create(url);
    objWebRequest.Method = "POST";
        
    // add sample form data
    ArrayList queryList = new ArrayList();
    queryList.Add(string.Format("{0}={1}", "value1","text1"));
    queryList.Add(string.Format("{0}={1}", "value2","text2"));
        
    // Set the encoding type
    objWebRequest.ContentType="application/x-www-form-urlencoded";
    string Parameters = String.Join("&",(String[]) queryList.ToArray(typeof(string)));
    objWebRequest.ContentLength = Parameters.Length;
        
    // Write stream
    StreamWriter sw = new StreamWriter(objWebRequest.GetRequestStream());
    sw.Write(Parameters);
    sw.Close();
        
    //we get back the response after submission
    HttpWebResponse objHttpWebResponse;
    objHttpWebResponse =  (HttpWebResponse)objWebRequest.GetResponse();
    StreamReader sr = new StreamReader(objHttpWebResponse.GetResponseStream());
        
    //we can print this out to see the response result
    //SEE BELOW RESPONSE.ASPX on HOW TO READ THE FORM DATA
    Response.Write(sr.ReadToEnd());
}

This is the response page that will grab the submitted data form.

    
//response.aspx
protected void Page_Load(object sender, EventArgs e){
    string value1 = "";
    string value2 = "";
    string strPost = "";
        
    //Loop the form data
    foreach (string strName in Request.Params) {
        string strValue = Request.Form[strName];
        //Request.Params(strName)
        switch (strName) {
            case "value1":
                value1 = strValue;
                break;
            case "value2":
                value2 = strValue;
                break;
        }

        //reconstruct post for postback validation
        strPost += string.Format("&{0}={1}", strName, Server.HtmlDecode(strValue));
    }
        
    //You can do anything you want with the value1 and value2
    //ex: we return string OK to client
    Response.Write("OK");
}

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.