Few days ago I had a case where I needed to make FORM POST from my ASP.NET WebForms page to another external site URL. More specifically, I was working on implementing Simple Payment System (like Amazon, PayPal, MoneyBookers). The operator asks to make FORM POST request to a given URL in their website, sending parameters together with the post which are computed on my application level (access keys, secret keys, signature, return-URL… etc). So, since we are not allowed nesting another form inside the <form runat=”server”> … </form>, which is required because other controls in my ASPX code work on server-side, I thought to inject the HTML and create FORM with method=”POST”.
After making some proof of concept and testing some scenarios, I’ve concluded that I can do this very fast in two ways:
- Using jQuery to create form on fly with the needed parameters and make submit()
Both ways seemed fine.
1. Using jQuery to create FORM html code and Submit it.
Let’s say we have ‘PAY NOW’ button in our ASPX code:
Now, if we want to make this button submit a FORM using POST method to another website, the jQuery way should be as follows:
Yes, as you see, the code fires on btnPayNow click. It removes the default button behavior, then creates htmlForm string. After that using jQuery we append the form to the body and submit it. Inside the form, you can see I have set the htttp://www.microsoft.com URL, so after clicking the button you should be automatically redirected to the Microsoft website (just for test, of course for Payment I’m using Operator's URL).
The C# code behind should be something like this:
This code runs on body load event, which means once the body is loaded the form is automatically submitted.
Note: In order to test both solutions, create two applications on your web server and post the form from first to the second website, then get the values in the second website using Request.Form[“input-field-id”]
I hope this was useful post for you.