how to write javascript in in code behind using C#

How can I write JavaScript code in in code behind using C#?

For example: I have click button event when I click the button I want to invoke this java script code:

alert("You pressed Me!"); 

I want to know how to use java script from code behind.



Actually, this is what you need:

string myScriptValue = "function callMe() {alert('You pressed Me!'); }";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "myScriptName", myScriptValue, true);

Copy all of javascript into string and then register it into your aspx page in code-behind. Then in aspx page, you can call the javascript function whenever you want. You should write this code in Page_Load method in C# page.


Have a look at the ScriptManager class' RegisterClientScriptBlock and RegisterStartupScript methods.


Not an answer, but a suggestion. Mixing your js within your code-behind can come back to haunt you, I agree with Adrian Magdas. Anytime you need to make a simple change/update to your javascript you'll have to re-build your project, which means re-deploying instead of simply pushing out a single .js file.


Something like:

btnSomething.ClientClick = "alert('You pressed me!');";

You might also want to read up on the ScriptManager control and outputting blocks of script.


The right answers usually is "You don't". It's better to define your code in a .js file and use jQuery to hook-up the desired events.

$(document).ready(function() {  
 $('#myBtn').click(function() {
  alert('Handler for .click() called.');

One way to put some javascript onto the page into a specific location do this:


<script type="text/javascript">
<asp:Literal id="litScript" runat="server" />


litScript.Text = "alert("Hello!");"

Of course, you can put anything in there, and I'd recommend a javascript library.

Using the Scriptmanager is also an option.


If you want to register a script that will be used in connection with an UpdatePanel (AJAX) use ScriptManager class as Sani Huttunen pointed. Otherwise you should use the class ClientScriptManager (methods Page.ClientScript.RegisterClientScriptBlock or Page.ClientScript.RegisterStartupScript)

As other user pointed, normally registering a script on the code behind can and should be avoided. It's not a very nice practice and you should do it only in cases where you have no other option.

Response.Write("<script language='javascript'>alert('You pressed Me!');</script>");


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.