Search code examples
c#javascriptasp.netdopostbackonclientclick

OnClick and OnClientClick


I have an image button on a pop up page which is opened by another page

<asp:ImageButton 
        ID="Button_kalem_islemikaydet" 
        runat="server" 
        CausesValidation="False" 
        ImageUrl="~/images/butonlar/buyuk/Kaydet.jpg"  
        meta:resourcekey="Button_kalem_islemikaydetResource1" 
        OnClick="Button_ust_islemikaydet_Click" 
        OnClientClick="f2()"  
        Width="100" />

f2() is

<script type="text/javascript">
        function f2() {
            opener.document.getElementById("TextBox1").value = "hello world";
            opener.document.getElementById("HiddenField1").value = "hello world";

            window.opener.location.href = window.opener.location.href;            
        } 
</script> 

And Button_ust_islemikaydet_Click is another method implemented in aspx.cs file and it updates the database tables which are shown in the parent page in a GridView.

What I am trying to do is to doPostBack I mean refresh the opener(parent) page.And with these above codes refresh is working.However, parent page still shows the same data before the refresh.And the reason is that OnClientClick works before OnClick method So my question is that is there any way I can run the method on OnClick and finish it and then run the OnClientClick method?


Solution

  • <form id="aspnetForm" runat="server">
        <asp:Button Text="Click Me" ID="ClickMeButton" OnClick="ClickMeButton_OnClick" runat="server" />
        <asp:HiddenField runat="server" ID="UpdateOpenerHiddenField" Value="false" />
    
        <script type="text/javascript">
            //1st approach
            var updateOpenerField = window.document.getElementById("<%= UpdateOpenerHiddenField.ClientID  %>");
            if (updateOpenerField.value === "true") {
                f2();
                updateOpenerField.value = "false";
            }
    
            // for the 2nd approach just do nothing
            function f2() {
                alert("Hello, opener!");
            }
    </script>
    </form>
    
    
    protected void ClickMeButton_OnClick(object sender, EventArgs e)
        {
            //1st approach
            UpdateOpenerHiddenField.Value = "true";
    
            // 2nd approach
            ClientScript.RegisterStartupScript(this.GetType(), "RefreshOpener", "f2();", true);
        }