Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Web Forms » Posting form data from ASP.NET page to another URL

Posting form data from ASP.NET page to another URL

This article shows you how to post a Form data to a different URL from ASP.NET pages. For example, you might need to send user to a third party payment processing system using post method. ASP.NET does not provide any straight forward way to accomplish this task.

Author Rank:
Technologies: .NET 1.0/1.1, ASP.NET 1.0,Visual C# .NET
Total downloads : 2696
Total page views :  127016
Rating :
 4.85/5
This article has been rated :  13 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
RemotePost.zip
 
Become a Sponsor



Introduction

Sometime you need to post a form to an different url from asp.net pages, for example you might need to send user to third party payment processing system using post method, asp.net does not provide any straight forward way to accomplish this task.

Problem which most users faces with server side form in aspx page are, you are not allowed to change action of form and you are allowed to use only one server side form per page.

Possible Solutions

  1. One possible solution to this problem is to Create your own form control and use it on page this will allow you to change action of form, but again what if you do not want some existing input elements in current page to go to post.
  2. There is good way to post form data using HttpWebResponse & HttpWebRequest class if you want to post data behind the scenes, but if you want to post data using user browser then you are stuck.

Our Solution

I will try to show you one possible way to accomplish this task, we will create

  1. component that will create form with required fields and post the form to specified url, 
  2. web page that will use that component to post data and 
  3. page which will receive that data and display posted data.

A) RemotePost Class.

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("");
System.Web.HttpContext.Current.Response.Write(
string.Format("",FormName));
System.Web.HttpContext.Current.Response.Write(
string.Format("",FormName,Method,Url))
for(int i=0;i< Inputs.Keys.Count;i++)
{
System.Web.HttpContext.Current.Response.Write(
string.Format("",Inputs.Keys[i],Inputs[Inputs.Keys[i]]));
}
System.Web.HttpContext.Current.Response.Write("");
System.Web.HttpContext.Current.Response.Write("");
System.Web.HttpContext.Current.Response.End();
}
}

Properties of our component 

  1. "Url" which is action of our form. 
  2. "Method" which is Method of our form, default is Post but you can also use Get 
  3. "FormName" which is name of form.

Methods of our component. 

  1. "Add" which will be used to add form input name and value. and 
  2. "Post" which will render html on page to do actual posting, most important part of this method is onload event of rendered html's body which will post form to specified URL.

and private field Inputs which will hold name value pair collection of all inputs that goes into form.

you can compile this class to dll and use in your project but for simplicity I am including that class directly into page itself.

B) Sample Page.

Following is sample page code which posts form to specified url.

RemotePost myremotepost = new RemotePost();
myremotepost.Url = http://www.jigar.net/demo/HttpRequestDemoServer.aspx;
myremotepost.Add("field1","Huckleberry");
myremotepost.Add("field2","Finn");
myremotepost.Post() ;

C) Receiving Page.

Following is sample page code which posts form to specified url.

This is the page where posting will occur for simplicity we will just write posed value so that we can know what was posted.

<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e){
if (Request.Form["field1" != null ){
Response.Write("field1 : " + Request.Form["field1" + "")}
if(Request.Form["field2" != null ){
Response.Write("field2 : " +Request.Form["field2" + "")}
}
</script> 

Run Sample

Click "http://www.jigar.net/demo/RemotePost.aspx" target="new">here to run sample

There will be cases where you will need to tweak the code to suit your requirement. you will also need to check scenario where user uses back button of browser(from posted page) which will cause form to be posted again.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Jigar Desai
Jigar Desai is a Microsoft certified professional and has 8 years of experience in Microsoft technologies, he is working in asp.net since pre beta releases and has extensive experience in developing database driven web application. When he is not working with asp.net and SqlServer he likes to do experiments with GDI+ and Content automation in webapplications.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
RemotePost.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
string formatting by martin On April 29, 2006

 

Hi desaijm,

 

Im trying to use you code, but unfortunately it is not working. Without knowing anything about the

System.Web.HttpContext.Current.Response

class, I have been debugging your code. And it is obvious to me, that something is wrong in the post() method.

System.Web.HttpContext.Current.Response.Write(string.Format("",FormName));

doesn't write anything at all, even though FormName has a value. I replaced

the line with

string a=(string.Format("",FormName));

And the string a is EMPTY. Dont know anything about the string.format method either, but i know that sending nothing DOES nothing.

 

Reply | Email | Delete | Modify | 
Re: string formatting by Mark On September 9, 2008
hi this code helps a lot with my payment processing app... 2 things i want the form1 to submit automatically onload rather than by a button. how do i do this ? the action url is passed from the calling page... how do i use this in remotepost.aspx rather than a hard coded one ? it will pass in the querystring probably... thanks
Reply | Email | Delete | Modify | 
C# Corner HTML problem? by Robert On February 21, 2007
I think the string.Format commands should have HTML instead of the empty strings. I wonder if it's a problem on this website that interpretted the HTML tags as actual tags instead of displaying them in the page. I tried to view source on the page but I can't see any tags so they must have been rendered out previously.
Reply | Email | Delete | Modify | 
Re: C# Corner HTML problem? by Michael On April 29, 2007

Yes, the HTML did get stripped.

To view what was supposed to be there, download the sample files (top right corner, right above the ad). It's not easy to type in here, so I'll just leave it to you to download it.

Dekker
www.WoodworkDetails.com

Reply | Email | Delete | Modify | 
Re: C# Corner HTML problem? by whoever On March 14, 2007
Nice trick. Thanks
Reply | Email | Delete | Modify | 
howto: Open in a new window by Henrik On May 2, 2007
Hi, I have used your code and it works fine - I have one question though; I can't have it to open in a new window - like 'target="_blank"' - any help?
Reply | Email | Delete | Modify | 
thanks by Dan On May 7, 2007
just what i needed
Reply | Email | Delete | Modify | 
Can't download by Anders On May 16, 2007
Clicking on zip-file leads to "empty" browser window. Right clicking and "Save target as.." leads to "No such interface supported". Vista problem / IE7 problem?
Reply | Email | Delete | Modify | 
cool by fabrizio On June 20, 2007
simple and effective
Reply | Email | Delete | Modify | 
No JavaScript??? by Ian On September 3, 2007
Hi, One criticism I have is that if the browser does not support JavaScript, the page will not be posted. IJ
Reply | Email | Delete | Modify | 
You are the man by Carlos On September 6, 2007
This is just exactly what i needed, damn, i had like 5 days breaking my head looking for this exactly thing, thank you very much, worked like a wonder once i found out what to put on those empty strings, xD
Reply | Email | Delete | Modify | 
hi by venkat On October 18, 2007
i developed one eshopping site . can i use this process to connect to sites like yourpay.com,paypal.com. How can i pass some of my details to those sites.. give me some examples how can i pass my values to yourpay.com.
Reply | Email | Delete | Modify | 
Using this with asp.net master pages? by Eric On October 28, 2007
How would i go about using this example if the form i want to submit is conntained in a content palceholder page that is attached to an asp.net master page?
Reply | Email | Delete | Modify | 
body onload function by Daniel On November 5, 2007
Hi your class is funcion correctly but i have a problem when open the pop up page, because the parent page is has been clear, how do i to avoid? or load page in the same page?... best regards.
Reply | Email | Delete | Modify | 
Re: body onload function by Amy On March 21, 2008
I have same issue. Have you got this issue resolved yet? Thanks,HZ.
Reply | Email | Delete | Modify | 
Re: body onload function by Denis On October 7, 2008
I use target="_blank" to point to a new page. In order to have the orginal page then reload I had to change the post method by adding a javascript calling a redirect after a second or so. This gives time for the form to post and then the page point back to the orginal page. Code below, changes in bold. Would love to see if someone else has a different/better solution.

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

    System.Web.HttpContext.Current.Response.Write("<html><head>");
    System.Web.HttpContext.Current.Response.Write("<script> function redirect() { window.location = 'Default.aspx'} </script>");

    System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit(); setTimeout('redirect()', 2000)\">", FormName));
    System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" target=\"_blank\" >", 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();
}
Reply | Email | Delete | Modify | 
Re: Re: body onload function by pay On November 17, 2008

I use below for resolve this problem.

Current.Response.Write(String.Format("</head><body onload=""document.{0}.submit(); window.history.back()"">", FormName))

Reply | Email | Delete | Modify | 
body onload function by Daniel On November 5, 2007
Hi your class is funcion correctly but i have a problem when open the pop up page, because the parent page is has been clear, how do i to avoid? or load page in the same page?... best regards.
Reply | Email | Delete | Modify | 
Thanks by Alex On December 11, 2007
Nice trick...it really helped me
Reply | Email | Delete | Modify | 
Could not get it to work by sree_sundaram On March 14, 2008
I am trying to get it to go to Paypal site. I have replicated the code exactly as is. However, the page does not navigate to Paypal site. Instead, it posts back to itself. I have tried setting the action property to an empty string in the form tog but it puts back to its own page (the default in ASP.NET 2.0). Any ideas will be appreciated.
Reply | Email | Delete | Modify | 
Browser back button by Jim On March 21, 2008
Is there any way to get the back button to go to the original page, ie the page before the 'generated' form submit page?
Reply | Email | Delete | Modify | 
2 questions by Mark On September 9, 2008
hi this code helps a lot with my payment processing app... 2 things i want the form1 to submit automatically onload rather than by a button. how do i do this ? the action url is passed from the calling page... how do i use this in remotepost.aspx rather than a hard coded one ? it will pass in the querystring probably... thanks
Reply | Email | Delete | Modify | 
2 questions by Mark On September 9, 2008
hi this code helps a lot with my payment processing app... 2 things i want the form1 to submit automatically onload rather than by a button. how do i do this ? the action url is passed from the calling page... how do i use this in remotepost.aspx rather than a hard coded one ? it will pass in the querystring probably... thanks
Reply | Email | Delete | Modify | 
2 questions by Mark On September 9, 2008
hi this code helps a lot with my payment processing app... 2 things i want the form1 to submit automatically onload rather than by a button. how do i do this ? the action url is passed from the calling page... how do i use this in remotepost.aspx rather than a hard coded one ? it will pass in the querystring probably... thanks
Reply | Email | Delete | Modify | 
2 questions by Mark On September 9, 2008
hi this code helps a lot with my payment processing app... 2 things i want the form1 to submit automatically onload rather than by a button. how do i do this ? the action url is passed from the calling page... how do i use this in remotepost.aspx rather than a hard coded one ? it will pass in the querystring probably... thanks
Reply | Email | Delete | Modify | 
remote post class by sathiya On October 16, 2008
This is working fine for me. But i got the exception "[System.Threading.ThreadAbortException] = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}" how can i restrict this one in my page Kindly help me on this Needs urgent Thanks Sathiya
Reply | Email | Delete | Modify | 
Was very helpful. Thanks. by Samir On February 6, 2009
Hi Jigar, This article came to my viewing just when I needed it. I wanted to post back a form back to 2 different pages based on certain condition. One of the page is classic asp. This helps me achieve that. Thanks Samir
Reply | Email | Delete | Modify | 
Thank you! by James On February 20, 2009
Thank you very much for posting this article. I was in a bind and it was exactly what I needed. I had to integrate a new asp.net form with and old asp paypal processor page. This code worked perfect! Note: I did need to download the code to get it to work. The code in the article did not work for me. Thank you again for posting this! James

www.alavri.com
Reply | Email | Delete | Modify | 
Thank You Very Much! by Jonny On March 11, 2009
This is exactly what I was looking for!
Reply | Email | Delete | Modify | 
Thank you!, Muchas Gracias Jigar by marcos On March 12, 2009

Después de mucho buscar encontré en tu artículo una brillante solución a cambiar la página de destino de un form usando C#. Muchas gracias por compartir.

También necesité descargar el adjunto para conseguir que funcionara.

Marcos

Reply | Email | Delete | Modify | 
Error by michael On May 20, 2009

Hi, thanks for the code.  I've converted it to vb.net, but i'm getting error Sys.WebForms.PageRequestManagerParserErrorException:  The message received fro mthe server could not be parsed.  Common causes for this error are when the sresponse is modofied by calls to Response.Write().respons filters, HpptModules, or server trace is enabled.

Details : Error parsing near '<html><head></head><'.
code 0

Url: http://localhost:1036/mysite.com/learnmore.aspx

can anyone tell me how to fix this...i'm a bit of a noob.

Public Class RemotePost

Private Inputs As New System.Collections.Specialized.NameValueCollection()

Public Url As String = ""

Public Method As String = "post"

Public FormName As String = "form1"

 

Public Sub Add(ByVal name As String, ByVal value As String)

Inputs.Add(name, value)

End Sub

 

Public Sub 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 i As Integer = 0 To Inputs.Keys.Count - 1

System.Web.HttpContext.Current.Response.Write(String.Format("<input name=""{0}"" type=""hidden"" value=""{1}"">", Inputs.Keys(i), Inputs(Inputs.Keys(i))))

Next

System.Web.HttpContext.Current.Response.Write("</form>")

System.Web.HttpContext.Current.Response.Write("</body></html>")

System.Web.HttpContext.Current.Response.[End]()

End Sub

End Class

Reply | Email | Delete | Modify | 
Re: Error by michael On May 20, 2009
Oh i'm calling the code from the submit button of an update panel by the way......does this matter?
Reply | Email | Delete | Modify | 
thanks by carlos On June 3, 2009
i think is a great code.  thanks.
Reply | Email | Delete | Modify | 
Excellent by jaime On July 13, 2009
Simple, nice!!!

Just a comment. The code shown is not right, so you have to download the code to get the correct version.

Thanks a lot.-
Reply | Email | Delete | Modify | 
Great Logic Sir... by Ashish On September 17, 2009
Ohh....Thats really great logic implemented with a great treak..so much impressive....Thanks..Thanks a lot....
Reply | Email | Delete | Modify | 
Great! by Maxence On September 30, 2009
This class is very useful, thanks a lot.

Warning: The good code is under the attached .zip
Reply | Email | Delete | Modify | 
Absolutely great! by Onur On October 31, 2009
Thank you Jigar. Your solution has been a great time saver. Instead of trying to figure out how to come up with a solution to this exact problem, I was able to use your solution with minor adjustments.

Note to viewers: Download the code in the zip format. The displayed program logic has been stripped of necessary html code.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved