RegisterClientScriptBlock confusion

ぃ、小莉子 提交于 2019-12-11 07:02:07

问题


My master web page contain JS code to override standard alerts with custom jQuery dialog boxes.

<script type="text/javascript" language="javascript">
        window.alert=function(alertMessage)
        {
          $.msgbox(alertMessage, {type: "info"});  
         }             
</script>

In default.aspx web page onLoad method I am trying to register and display alert script

 Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "InvalidPassword",
                "alert(\"Your login attempt was not successful. Please try again.\");",
                true);

Unfortunately it does not work. If I remove JS code which override alert box everything works fine, alert box appears. The override JS is correct, it is working fine if I execute alert js in client side, but it does not work if I try to execute code from server side.

Could anyone explain where is the problem?


回答1:


I get the same problem when I try to run it from the page_load event of the aspx page, but when I run it from the body onload event it works. I think this is happening because the page_load event occurs before your window.alert override has a chance to be run.

Try this in the body tag:

<body onload="alert('Your login attempt was not successful. Please try again.');">  

And the jQuery:

$(function () {

        window.alert = function (message) {
            $('#dialog').text(message).dialog();
        }

 });

I used the jQuery UI dialog plugin by the way.




回答2:


Ok, I found where is the problem. If code registered with RegisterClientScriptBlock refer to another JS code then we need to load web page in full. It seems that JS registered in RegisterClientScriptBlock executed immediate when it is loaded in browser no matter if web page loaded in full or not. So we need to execute code after web page loaded fully. We can use jQuery event below to find it

  $(document).ready(function() {



  });

The full code will look like

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "InvalidPassword",
                    "$(document).ready(function() {alert(\"Your login attempt was not successful. Please try again.\");})",
                    true);


来源:https://stackoverflow.com/questions/3684596/registerclientscriptblock-confusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!