Welcome to AspAdvice Sign in | Join | Help

Cross-page postback and form action

I was asked some time ago if one can cross.page post to a new window and I replied with

You can control where the post targets by changing form's action with script. For example:

<asp:Button ID="Button1" OnClientClick="form1.target='_blank'"
runat="server" Text="Button" PostBackUrl="~/Default2.aspx" />

If you open a popup window with script and then put window's name to form's target, it should post to that window.

Now, I was also asked how to change the target/action back after this button has doner with postback. For example a scenario where second button still postbacks normally on the same page. Here's the quick test bed I used (relevant snippets).

WebForm1.aspx

<form id="form1" runat="server">
    <div>
       

        <asp:Button ID="btnCrossPagePostBack" OnClientClick="theForm.target='_blank'"
        runat="server" Text="Button" PostBackUrl="~/WebForm2.aspx" />
        <asp:Button ID="btnPostback"  runat="server" Text="Do a reguar postback" OnClick="btnPostback_Click"  /><br />
        <asp:Label ID="lblMessage" runat="server"></asp:Label></div>
       
        <script>
            var btn=document.getElementById('<%=btnCrossPagePostBack.ClientID%>');
            var oldClick=btn.onclick;
            
           
            function myClick()
            {
                oldClick();
               
                //set the target/action back after 200 milliseconds
                window.setTimeout("theForm.target='_self';theForm.action='WebForm1.aspx'",200);
            }
           
            btn.onclick=myClick;
           
        </script>
    </form>

WebForm1.aspx.cs

protected void btnPostback_Click(object sender, EventArgs e)
        {
            lblMessage.Text = DateTime.Now.ToShortDateString() + " Standard postback!";
        }

WebForm2.aspx

<form id="form1" runat="server">
    <div>
        <asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label>
    </div>
    </form>

WebForm2.aspx.cs

protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.PreviousPage != null)
                lblMessage.Text = DateTime.Now.ToShortDateString() + "Page opened via a cross-page post";
        }

Published Thursday, November 30, 2006 10:34 PM by joteke
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Cross-page postback and form action

gr8!!!!! it works.....
Tuesday, March 23, 2010 9:32 AM by Amit jain

# re: Cross-page postback and form action

when i click the button it is also opened in new window with WebForm2.aspx
Friday, October 29, 2010 12:25 PM by shiva

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below