Learn how to write and execute the javascript code from c# code behind

In this tutorial you will learn how to write and execute the javascript code from c# code behind. Sometimes you may want to execute the javascript code directly from c# code behind. For example, you want to do so when a condition matches in your c# code like this
string name;
string std_name;

if(name==std_name)
{
//Now here you want to execute your javascript code
}

Learn how to write and execute the javascript code from c# code behind


In my .aspx page I am using a <span id="showMessage">and <asp:button>. When you will click the <asp:button>, focus will go to the server side then there I have written my code that will alert a message and display my name in the <span id="showMessage">. Let’s have a look over how to do so
protected void submit_Click(object sender, EventArgs e)
{

string popupScript = "<script language='javascript'>" +
"function GetAlert(){" +
"document.getElementById('showMessage').innerHTML = 'Adeel Fakhar';" +
"alert('Function is being called');" +
"}" +
"GetAlert()" +
"</script>";
Page.RegisterStartupScript("Startup", popupScript);
}

Page.RegisterStartupScript is used for registering and executing the client side script. This method takes two parameters. First one is key of type System.String and it acts as a unique key that identifies a script block. Second parameter is script which type is also System.String, it is content of script that will be sent to the client, means it contains your javascript code.

Page.RegisterStartupScript automatically attach the script just before the closing tag of your aspx page object’s <form runat="server">
element.

Page.RegisterStartupScript method uses a unique key to identify the script block; the script block does not have to be emitted to the output stream every time it is requested by a different server control instance.

Any script block with the same key parameter values is considered duplicate. You must remember to include HTML Comment Tags around your script so that it will not be rendered if the requesting browser does not support javascript.

So this is the way to write and execute the javascript code from c# code behind.
Read more...