Skip to content Skip to sidebar Skip to footer

Call Javascript Function From Asp.net Code Behind After Server Side Code Executes

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.

Solution 1:

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:

voidmyButton_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.

Solution 2:

JavaScript is a client side technology.

While I suppose it would be theoretically possible to run the code on the server I don't see what benefit it would give you.

What do you actually want to achieve?

Post a Comment for "Call Javascript Function From Asp.net Code Behind After Server Side Code Executes"