Javascript – Call javascript function from asp.net code behind after server side code executes

asp.netjavascript

I have an asp.net button, that when clicked calls a code behind function. The function does some evaluation, and then I want to call javascript from within this asp.net function.

Best Answer

While pranay's answer is correct in the function call, the rest is off, here's hopefully a better explanation:

You can use ClientScript.RegisterStartupScript() to do what you want, like this:

void myButton_Click(object sender, EventArgs e)
{
  var script = "alert('hi');";    
  ClientScript.RegisterStartupScript(typeof(Page), "ButtonAlert", script, true);
}

The format is (type, scriptKey, scriptText, wrapItInScriptTags).

If you are operating with an UpdatePanel, it's very similar, except you need to use the slightly different ScriptManager.ResgisterStartupScript(). Use the UpdatePanel as the control and type parameters in that case to be safe.