What is the best way to close an ASPX page from the code-behind?
I have a button event handler that I want to close the page after the user has clicked an ASP.NET
You should inject a startup script that will close the page after the postback has finished.
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>");
You just need to add this property in your asp:Button element (for example):
OnClientClick="javascript:window.close();"
It works perfectly.
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Attributes.Add("onclick"," CloseWindow();");
}
<script type="text/javascript">
function CloseWindow()
{
window.close();
}
</script>
You can just simply use this.. short and easy.
Response.Write("<script>window.close();</script>");
Hope this helps.
For anyone wondering why they cannot get the provided answers to work it's because the page must have been opened by javascript in order to be closed by javascript.
Since most people finding this asp question are likely using an asp:hyperlink
or an asp redirect of some sort to navigate to the page that needs to be closed. These methods of redirection don't use javascript and therefore will not close by javascript.
I found a simple solution for my application and that's eliminating the NavigateUrl
and using the asp:Hyperlink.Attributes
to add an onclick
to the hyperlink which uses java script to open the window that needs to be closed by javascript.
aspHyperlink.NavigateUrl = "https://www.google.com";
The above NavigateUrl is removed and instead we attach our click event.
aspHyperlink.Attributes.Add("onclick", "javascript:openInNewTab('https://www.google.com');");
And in the code behind of the page containing our aspHyperlink we have the javascript for opening the url provided by Rinto
function openInNewTab(url) {
var win = window.open(url, '_blank');
win.focus();
}
Now all pages opened with openInNewTab
can be closed with the provided answers.
window.close();
If you using RadAjaxManager then here is the code which helps:
RadAjaxManager1.ResponseScripts.Add("window.opener.location.href = '../CaseManagement/LCCase.aspx?" + caseId + "';
window.close();");