Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write javascript in asp.net in code behind using C#

How can I write JavaScript code in asp.net 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.

like image 699
Eyla Avatar asked May 17 '10 10:05

Eyla


People also ask

How use JavaScript code behind in asp net?

Codebehind is running on the server while JavaScript is running on the client. However, you can add <script type="text/javascript">someFunction();</script> to your output and thus cause the JS function to be called when the browser is parsing your markup. "You cannot. But here is how you do it."

How Register JavaScript code behind in C#?

Solution 2Both RegisterClientScript and RegisterStartupScript use to add javascript code in web form between <form runat="server"> tag and </form> tag. RegisterClientScript adds javascript code just after <form runat="server"> tag while RegisterStartupScript adds javascript code just before </form> tag.

Can we use JavaScript in asp net C#?

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

Where do I put JavaScript code in asp net?

Either you can add your JavaScript code inside head tag of your Aspx page. Or add new . js file in your Project, write your JavaScript code inside it and then reference it in your Aspx page. 2) With Master-Content Pages.


2 Answers

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.

like image 182
Tri Nguyen Dung Avatar answered Sep 24 '22 17:09

Tri Nguyen Dung


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

like image 27
Sani Singh Huttunen Avatar answered Sep 23 '22 17:09

Sani Singh Huttunen