Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
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 :
Page Views : 249823
Downloads : 5004
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
RemotePost.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
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 | 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 | 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 | 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 | Modify 
Re: C# Corner HTML problem? by whoever On March 14, 2007
Nice trick. Thanks
Reply | Email | 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 | Modify 
thanks by Dan On May 7, 2007
just what i needed
Reply | Email | 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 | Modify 
cool by fabrizio On June 20, 2007
simple and effective
Reply | Email | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | Modify 
Thanks by Alex On December 11, 2007
Nice trick...it really helped me
Reply | Email | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | Modify 
Thank You Very Much! by Jonny On March 11, 2009
This is exactly what I was looking for!
Reply | Email | 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 | 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 | 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 | Modify 
Re: Error by Robert On August 18, 2010
I've got the same problem as you but I am using the downloaded code... Does anyone know about this?
Reply | Email | Modify 
Re: Re: Error by Robert On August 19, 2010

*** If you place a button in an update panel, and you call RemotePost.Post() in the code behind, you will get an error because of ajax. The solution is to place a html button in the update panel which calls a javascript function which clicks a hidden button that is not in an update panel. Then in the code behind in the handler for the hidden button you can call RemotePost.Post().

Reply | Email | Modify 
thanks by carlos On June 3, 2009
i think is a great code.  thanks.
Reply | Email | 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 | 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 | 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 | 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 | Modify 
What about browser's "Back" button?? by Alex On February 19, 2010
Hello. The solution quite good but have one hardship.  The browser's "Back" button won't be work after redirection.
Reply | Email | Modify 
Pooblem with Post data to another site by Vivek On April 21, 2010

Hi Jigar,

I want to post some values (Title, Description, price etc.) from my local page to another web page of different website. the another website page has same fields (Title, Description, Price etc). I want to copy data deom my site to another site. I have and account on another website to post my data on server. What I will do?

Reply | Email | Modify 
Thanks by Mark On April 21, 2010
This was just what I needed, some times its difficult to see a simpler more elegant solution like this.

Mark
Reply | Email | Modify 
Thanks! by Paul On May 12, 2010
Thank you!  I got it to work as a web user control within the SmartPart web part in SharePoint!

Paul
Reply | Email | Modify 
THANKS!!!! by Bris On May 24, 2010
Very good solution!!. Thanks :)
Reply | Email | Modify 
Clever by Rich On May 26, 2010
Clever idea.
Easy to use.
Well explained.

Just a shame we have to resort to tricks like this in .NET.

Rich
Reply | Email | Modify 
is it possible to show that new url in a modal Dialog using showModalDialog by sharon On June 8, 2010
I need my website to post to another 3rd party website (which would be super if it's in a modal dialog), do some stuff there (it's not a webservice, it's a website on another domain which i don't control) and come back to my website without losing session. The other website will use post back to come back on my website.
Is that feasable? I've been cracking my head open to find a solution to this for a week, any help would be greatly appreciated!! :)
Reply | Email | Modify 
Great by srk69 On June 18, 2010
Just what I was looking for!
Reply | Email | Modify 
Without putting code of page load on receving page by Ankur On August 4, 2010

Hi Jigar Desai,
 The code is working fine for me. But i need to put the code on receiving page. How to implement this without puttin the code on receiving page since i dont have any control over it.

Thanks.

Reply | Email | Modify 
Remote Post by Athi On August 6, 2010
This is very useful to me. Thanks!!!!
Reply | Email | Modify 
Redirect Post with ASP.NET MVC by Dean On August 17, 2010
Hi,
I'm trying to get redirect via POST working with ASP.NET MVC. I'm using the code above as  starting place, but I'm having trouble figuring out how to redirect to the URL instead of processing the result back. It's almost similar to the Redirect(url) command except it needs to accept a POST.
Any ideas?
Thanks,
Dean
Reply | Email | Modify 
Nice work by aaa On December 22, 2010
Thanks very much, code worked perfectly and did exactly what I wanted it to do. Bruce
Reply | Email | Modify 
Feedback by manish On February 9, 2011
simple and beautiful.......... Thanks!
Reply | Email | Modify 
thanks you! by Brian On March 25, 2011
This posting was very useful to me, there is only one snag. Where you have used string.Form, the html has been remove so that it reads simply "" for example System.Web.HttpContext.Current.Response.Write(""); should be System.Web.HttpContext.Current.Response.Write("<html><head>");
Reply | Email | Modify 
tag html be hidden by An On June 14, 2011
thanks
Reply | Email | Modify 
Perfect! by Laura On October 25, 2011
Exactly what I was looking for! Thanks so much!
Reply | Email | Modify 
Nice by Raju On October 28, 2011
Thanks
Reply | Email | Modify 
Bunch of thanks by K V Reddy On November 7, 2011
your artile helped a lot, bunch of thanks.
Reply | Email | Modify 
Great thanks - how about this for non-Javascript users by Steve On January 27, 2012
An old post, but still I found this very useful thanks. I suggest an addition to support those who do not have Javascript support or have it enabled, because of course otherwise they will just see a blank page... I apologise in advance if the syntax below is incorrect, as C is not my native language! ...Add after input loop and before closing /form tag.... /* ---Add message and submit button for non-Javascript users */ System.Web.HttpContext.Current.Response.Write("<p>If you see this message for more than a few seconds please click the button below to continue.</p>"); System.Web.HttpContext.Current.Response.Write("<input id=\"Submit1\" type=\"submit\" value=\"Continue\" />""); /* --- */
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.