简体   繁体   中英

Call a Javascript function AFTER the Server Onclick event

I have this code for a click event of a button:

protected void Button1_Click(object sender, EventArgs e)
{
    string message = "";
    //Series of codes to change the message variable

    Page.ClientScript.RegisterStartupScript(GetType(), "", "ShowMessage(" + message +");", true);
    }



<script type="text/javascript">
    function ShowMessage(msg){
        alert(msg);
    }
</script>

and this won't display the message. maybe my RegisterStartupScript is incorrect?

Try followings,

  1. You have to give a valid name for your script. http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx

    A startup script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates. Only one script with a given type and key pair can be registered with the page. Attempting to register a script that is already registered does not create a duplicate of the script.

  2. ShowMessage should be defined in the page

  3. You have to pass the parameter as string. ShowMessage('" + message +"');

  4. Final code should like this

Page.ClientScript.RegisterStartupScript(GetType(), "myAlertScript", "ShowMessage('" + message +"');", true);

UPDATE


If you have update panels in the page, try following code instead.

ScriptManager.RegisterClientScriptBlock(this,typeof(Page),"myAlertScript","ShowMessage('" + message +"');", true);

在对ShowMessage的调用中,您缺少message变量周围的引号,请尝试以下操作:

Page.ClientScript.RegisterStartupScript(this.GetType(), "", "ShowMessage(\"" + message + "\");", true);

To test if the message is delivered to the client you can simply call a native javascript function that'll rule out any client side issues.

Page.ClientScript.RegisterStartupScript(GetType(), "", "alert('here?');", true);

You can also view the source of a page in your browser to see if the code is being delivered to the client.

To execute code after the click handler (and anything it calls) is complete, set a timeout during the handler.

function onClick() {
    window.setTimeout(functionToCall, 0);
}

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