Sunday, October 21, 2012

Refresh parent page from child window using javascript in asp.net web application

Much often we open child windows from parent web page. In the child page we perform some activities, and later close the window. At the very time we may need to refresh the parent page so that changes made in the child window be reflected in the parent window. We can easily accomplish this using javascript in asp.net web page. Let me show the way using code snippets. If it is your iframe page, you still can refresh the parent page partially from page in iframe (because this will avoid reloading the iframe itself), which I have discussed in another post. And right before following, I would like to inform that there is a post regarding Frequent question on parent and child page refresh, reload, function call in asp-net using javascript that discusses, in aggregate, about some more approaches of parent and child page operations.

Parent asp.net web page



  1. <form id="form1" runat="server"><div><asp:hyperlink id="hlink1" runat="server" navigateurl="Child.aspx" target="_blank">Open child window</asp:hyperlink>          
  2.     </div></form>  
This is the parent page. Clicking the link will open the child page Child.aspx in a new window. If you wish you can Open the new window in asp.net web page in different ways, which I have already discussed in a previous post.

Child asp.net web page



  1. <form id="form1" runat="server"><div><p>This is the child page.</p><asp:button id="btnOk" runat="server" onclick="btnOk_Click" text="OK">          
  2.     </asp:button></div></form>  

  1. protected void btnOk_Click(object sender, EventArgs e)  
  2.     {   
  3.         //Implement Your logic here.....  
  4.         //..............................  
  5.         //now refresh parent page and close this window  
  6.         string script = "this.window.opener.location=this.window.opener.location;this.window.close();";  
  7.         if (!ClientScript.IsClientScriptBlockRegistered("REFRESH_PARENT"))  
  8.             ClientScript.RegisterClientScriptBlock(typeof(string), "REFRESH_PARENT", script, true);          
  9.     }  
In the child page, I have just put a button. When the button is clicked, the page logic will be implemented (which I have indicated by the comment lines in the event handler of the button in the asp.net child page).

The asp.net plus javascript logic

I have just created the javascript stuff that refreshes the parent page of this child page; see the lines:
this.window.opener.location=this.window.opener.location;this.window.close();
This line replaces the url of the parent page with its own url - that causes the parent page to reload. And yes, I have registered the javascript code block with ClientScript so that it is executed when the postback life cycle of this child page completes.