Sometime you want to post your web form to another page (or to page of any third party application) in order to pass some value to another application. But problem most of ASP.NET developers faces here, is that they cannot set action attribute of the form if the form is server side control.
If I set action attribute of form tag like this:
WebForm1.aspx (Web Page):
<form id="Form1" method="post" runat="server" action="WebForm2.aspx">
</form>
Than ASP.NET will automatically remove this attribute from the form and set it to page name itself while rendering that HTML form. This is the way page PostBack mechanism works in ASP.NET (1.1). So rendered HTML code will look like this:
Rendered HTML Page:
<form name="Form1" method="post" action="WebForm1.aspx" id="Form1">
</form>
You can set action attribute if you remove Runat=”server” from your form tag. This works fine till you find that you cannot place server controls like Button, TextBox, ImageButton in that form. Placing button control inside Form without runat=”server” will gived ASP.NET error:
Control 'imageButtonSubmit' of type 'ImageButton' must be placed inside a form tag with runat=server.
To address this kind of typical requirement, here is the small javascript hack which allow you to post your form to another page, and yet you have all of those required server controls in that form.
<form id="Form1" method="post" runat="server" onsubmit="document.Form1.action='WebForm2.aspx';">
<asp:ImageButton Runat="server" ImageUrl="Image/Post.gif" BorderWidth="0" ID="Post" ></asp:ImageButton>
</form>
Here is the practical implementation of using this hack for calling PayPal web page:
<form id="Form1" method="post" runat="server" onsubmit="document.Form1.action = 'https://www.sandbox.paypal.com/cgi-bin/webscr';">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="mail@webtest.com">
<input type="hidden" name="item_name" value="ABC Item">
<input type="hidden" name="item_number" value="SKU-1234">
<input type="hidden" name="amount" value="10.00">
<input type="hidden" name="no_shipping" value="0">
<input type="hidden" name="no_note" value="0">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="bn" value="PP-BuyNowBF">
<asp:ImageButton Runat="server" ImageUrl="https://www.sandbox.paypal.com/en_US/i/btn/x-click-but23.gif" BorderWidth="0" ID="submit" AlternateText="Make payments with PayPal - it's fast, free and secure!"></asp:ImageButton>
</form>
One comment
Leave a reply