Programmatically close aspx page from code behind

前端 未结 13 2105
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 05:05

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

相关标签:
13条回答
  • 2020-11-29 05:33

    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>"); 
    
    0 讨论(0)
  • 2020-11-29 05:33

    You just need to add this property in your asp:Button element (for example):

    OnClientClick="javascript:window.close();"
    

    It works perfectly.

    0 讨论(0)
  • 2020-11-29 05:34
      protected void Button1_Click(object sender, EventArgs e)
      {
        Button1.Attributes.Add("onclick"," CloseWindow();");
      }
    
        <script type="text/javascript">
            function CloseWindow() 
          {
             window.close();
          }
        </script>
    
    0 讨论(0)
  • 2020-11-29 05:34

    You can just simply use this.. short and easy.

    Response.Write("<script>window.close();</script>");
    

    Hope this helps.

    0 讨论(0)
  • 2020-11-29 05:39

    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();
    
    0 讨论(0)
  • 2020-11-29 05:44

    If you using RadAjaxManager then here is the code which helps:

    RadAjaxManager1.ResponseScripts.Add("window.opener.location.href = '../CaseManagement/LCCase.aspx?" + caseId + "'; 
    window.close();");
    
    0 讨论(0)
提交回复
热议问题