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.
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."
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.
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With