Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call javascript function from code-behind

I wrote a javascript with a asp.net page.

In Asp.net Page

<HTML> <HEAD>      <script type="text/javascript">       function Myfunction(){           document.getElementId('MyText').value="hi";       }       </script> </HEAD> <BODY> <input type="text" id="MyText" runat="server" /> </BODY> 

In Code-behind

 Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Me.Load        If Session("My")= "Hi" Then           I want to call "Myfunction" javascript function        End If   End Sub 

How can I do?

like image 648
zanhtet Avatar asked Jan 31 '11 07:01

zanhtet


People also ask

How do I call a JavaScript function from code behind?

What you can do to call a method from server using JavaScript is. Use WebMethod as attribute in target methods. Add ScriptManager setting EnablePageMethods as true . Add JavaScript code to call the methods through the object PageMethods .

How do you call a client side JavaScript function from the server side?

The JavaScript Client Side function will be called from Code Behind (Server Side) using ClientScript RegisterStartupScript method. The following HTML Markup consists of an ASP.Net Button and a Label control.

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.


2 Answers

One way of doing it is to use the ClientScriptManager:

Page.ClientScript.RegisterStartupScript(     GetType(),      "MyKey",      "Myfunction();",      true); 
like image 72
Jacob Avatar answered Oct 16 '22 17:10

Jacob


This is a way to invoke one or more JavaScript methods from the code behind. By using Script Manager we can call the methods in sequence. Consider the below code for example.

ScriptManager.RegisterStartupScript(this, typeof(Page), "UpdateMsg",      "$(document).ready(function(){EnableControls();     alert('Overrides successfully Updated.');     DisableControls();});",  true); 

In this first method EnableControls() is invoked. Next the alert will be displayed. Next the DisableControls() method will be invoked.

like image 41
Deepak Kothari Avatar answered Oct 16 '22 17:10

Deepak Kothari