Posting ASP.NET form to another page.

Sometime ASP.NET developers require to post web form to another page (or may be to the third party application page) in order to pass some values. But problem most developers faces here, is that they cannot set action attribute if form is server side control. If I set action attribute of form tag something like this:

WebForm1.aspx Page:
<form id="Form1" method="post" runat="server" action="WebForm2.aspx"> </form>

then ASP.NET will automatically remove this attribute from the form and set it to page name itself while rendering HTML. This is the way page PostBack mechanism works in ASP.NET (1.1).

So rendered HTML 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 throw ASP.NET exception:

Control 'imageButtonSubmit' of type 'ImageButton' must be placed inside a form tag with runat=server.

To address this kind of typical form requirement, following is the small Javascript hack which allow you to post your form to another page, and yet you can have your server controls in the 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>