简体   繁体   中英

ScriptManager.RegisterClientScriptBlock Doesn't Call Existing Script

Background

I have a client-side button click that triggers a server-side function. Before the server side function is called, a loading panel is displayed (div).

The loading panel needs to be removed once the server-side function has completed.

My Solution

After the server-side function is complete I will call a JavaScript function that will remove the div. So as a test i'm calling an alert script. I'm trying to do this from the master page.

Client-Side Code

My PopUp Function

    <script>
        function PopUp() {
        debugger;
        alert('TEST');
        }
     </script>

My Script Manager

 <asp:ScriptManager ID="ScriptManager1" runat="server">
 </asp:ScriptManager>

Server-Side Code

My Call after server side functions have completed.

//Add the script  after <form> tag
   bool isClientScriptBlockRegistered = ClientScript.IsClientScriptBlockRegistered("ShowStatus");
   if (!isClientScriptBlockRegistered)
   {
   ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowStatus", "PopUp();", true);
   }

Problem

My script isn't called by the server. No alert window is created. When I try to do this from any page other that the master page it works. However on the master page it does not.

Questions

Is there something I'm missing?

Does there need to be a callback or some kind of refreshing of the page for the alert to appear, or can the server just call the script without any action from the client?

Change

ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowStatus", "PopUp();", true);

into

ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowStatus", "setTimeout(function () {  PopUp(); }, 10);", true);

or into

ScriptManager.RegisterStartupScript(Page, Page.GetType(), "ShowStatus", "PopUp();", true);

RegisterClientScriptBlock adds the JavaScript code at the top of the page just after the ViewState tag while RegisterClientScriptBlock adds it to the bottom. So if you use RegisterClientScriptBlock and your PopUp() is somewhere lower on the page you'll get an error.

Or by setting a setTimeout you ensure that all the contents is generated and then PopUp() will also be found even is the script block is at the top.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM