Click here to Skip to main content
Click here to Skip to main content
Go to top

Post form data to another URL in ASP.NET 1.1

, 16 Jan 2007
Rate this:
Please Sign up or sign in to vote.
I am a web developer. I worked for oil company in China before I came to Canada.

Introduction

I need post form data to another URL in ASP.NET 1.1. After I searched it on internet, I found following methods.

1. Use "Response.Clear()", "Response.Write()" and "Response.End()". It could post data to same page, but it could not post data to URL in a new window. Also I will will break "Back" button in browser.

2. Use HttpWebRequestion and HttpWebResponse to send request to server and get reponse. It returnes all page information in HTML. So we have to go through HTML to find useful data.

3. Post form data using Javascript. But I could not use it in user control, since I could not create multiple forms dynamically.

Demo Codes

I would like give some demo codes for 3 methos as following,

1. 

public class RemotePost
{
private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();


public string Url = "";
public string Method = "post";
public string FormName = "form1";

public void Add(string name,string value)
{
Inputs.Add(name,value);
}

public void Post()
{
System.Web.HttpContext.Current.Response.Clear();

System.Web.HttpContext.Current.Response.Write("<html><head>");

System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">",FormName));
System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >",FormName,Method,Url));
for(int i=0;i< Inputs.Keys.Count;i++)
{
System.Web.HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">",Inputs.Keys[i],Inputs[Inputs.Keys[i]]));
}
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body></html>");

System.Web.HttpContext.Current.Response.End();
}
}

In ASP.NET:

RemotePost m = new RemotePost();
m.Url = "test.aspx";

m.Add( "para1" ,"123456" );
m.Add( "para2" ,"0001" );
m.Post();

Please pay attention on "onload" event, form will be posted automatically.

 

2.http://authors.aspalliance.com/stevesmith/articles/netscrape2.asp

/stevesmith/articles/examples/cs/postscrape.aspx

<%@ Import Namespace="System.Net" %>

<%@ Import Namespace="System.IO" %>

<script language="C#" runat="server">

   void Page_Load(Object Src, EventArgs E) {

      myPage.Text = readHtmlPage("http://aspalliance.com/aldotnet/examples/posttest.asp");

   }



   private String readHtmlPage(string url)

   {

      String result = "";

      String strPost = "x=1&y=2&z=YouPostedOk";

      StreamWriter myWriter = null;

      

      HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);

      objRequest.Method = "POST";

      objRequest.ContentLength = strPost.Length;

      objRequest.ContentType = "application/x-www-form-urlencoded";

      

      try

      {

         myWriter = new StreamWriter(objRequest.GetRequestStream());

         myWriter.Write(strPost);

      }

      catch (Exception e)

      {

         return e.Message;

      }

      finally {

         myWriter.Close();

      }

         

      HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();

      using (StreamReader sr =

         new StreamReader(objResponse.GetResponseStream()) )

      {

         result = sr.ReadToEnd();



         // Close and clean up the StreamReader

         sr.Close();

      }

      return result;

   }   

</script>

<html>

<body>

<b>This content is being populated from a separate HTTP request to

<a href="http://aspalliance.com/aldotnet/examples/posttest.asp">

http://aspalliance.com/aldotnet/examples/posttest.asp</a>:</b><hr/>

<asp:literal id="myPage" runat="server"/>

</body>

</html>

 

3. http://www.codeproject.com/aspnet/jsnopostback.asp

<div id="Content" name="Content">

    <form method="post" id="Form1" runat="server">

 

    </form>

</div>

The JavaScript now needs to differentiate between Netscape 4 and the other DOM aware browsers. Check for document.layers to identify Netscape 4, and simply use the syntax appropriate for that browser:

<script language="javascript">

<!--

function noPostBack(sNewFormAction)

{

    if(document.layers) //The browser is Netscape 4

    {

        document.layers['Content'].document.forms[0].__VIEWSTATE.name =

                                                           'NOVIEWSTATE';

        document.layers['Content'].document.forms[0].action =

                                                     sNewFormAction;

    }

    else //It is some other browser that understands the DOM

    {

        document.forms[0].action = sNewFormAction;

        document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';

    }

}

-->

</script>

 

 

Improvement.

 

My coworker gave me some good ideas, I choose 3rd method and improve it as my solution. Everytime, form and hidden fields are created dynamically, so it could handle form and fields as many as I wish. Also it could be used in user control, since all function is done on client side.

 

//Creat form dynamically and post data to specified URL
//formName: the name of form
//formAction: the URL
//hidden input fields, like fieldname1=fieldvalue1&fieldname2=fieldvalue2
function postForm(formName,formAction,arrayStr,newWindow)
{
var frm=cf(formName,formAction,newWindow);
var inputArray=arrayStr.split('&');
for(var j=0;j<inputArray.length;j++)
{
var temp=inputArray[j].split('=');
if(isArray(temp) && temp.length==2)
{
cfi(frm,temp[0],temp[1])
}
}
frm.submit();
}
//Check whether variable is array
function isArray(obj) {
if (obj.constructor.toString().indexOf('Array') == -1)
return false;
else
return true;
}
function cf(name,action,newWindow) {
var f = document.createElement('FORM');
f.method='POST';
f.name=name;
f.action=action;
if(newWindow)
f.target='_blank';
document.body.appendChild(f);
return f;
}
function cfi(parentForm,name,value) {
var i = document.createElement('INPUT');
i.type='hidden';
i.name=name;
i.value=value;
parentForm.appendChild(i);
}

 

in ASP.NET,

HyperLink hl;

string arrStr="fieldname1=fieldvalue1&fieldname2=fieldvalue2";

hl.NagativeUrl="#";

hl.Attributes.Add("onclick","postForm('PostedData','getpost.aspx','"+arrStr+"',true);return false;");

 

If anyone knows how to implement same function on server side, please let me know. Thanks.

 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

baoshenyi
Web Developer
Canada Canada
No Biography provided

Comments and Discussions

 
GeneralExactly what I needed Pinmembersparks_2193-May-07 6:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 17 Jan 2007
Article Copyright 2007 by baoshenyi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid