ASP.NET front and back calls the method

  • 2020-05-07 19:31:07
  • OfStack

1.JavaScript accesses the C# function
2.JavaScript accesses C# variable
3. Access the existing variables of JavaScript in C#
4. How do I access the JavaScript function in C#
JavaScript accesses the C# function
method 1.
1. First, create a button and write the contents of the call or processing to button_click in the background;
2. Write one js function in the foreground, document.getElementById ("btn1").click ();
3. Call js function in the foreground or background, fire click event, equal to access the background c# function;
method 2.
1. Functions are declared as public or protected
 
public string Hello() 
{ 
return("Hello World"); 
} 

2. In html < %=fucntion()% > You can call
 
<html xmlns="http://www.w3.org/1999/xhtml%22> 
<head runat="server"> 
<title>Untitled Page</title> 
<script language="javascript" type="text/javascript"> 
function say() 
{ 
var strHello = "<%=Hello()%>"; 
alert(strHello); 
} 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="say();" /> 
</div> 
</form> 
</body> 
</html> 

method 3.
 
<script language="javascript"> 
function __doPostBack(eventTarget, eventArgument) 
{ 
var frontForm = document.Form1; // Refers to the runat=server the form 
frontForm.__EVENTTARGET.value = eventTarget; 
frontForm.__EVENTARGUMENT.value = eventArgument; 
frontForm.submit(); 
} 
</script> 
<input id="Button1" type="button" name="Button1" value=" button " onclick="javascript:__doPostBack('Button1','')"> 

Access the C# variable in JavaScript
Method 1:1, through the page on the hidden field access < input id="xx" type="hidden" runat="server" >
Method 2:1, such as the background defined PUBLIC STRING N; The format of the reference to this variable in foreground js is' < %=n% > 'or "+ < %=n% > +"
Method 3:1, or you can register a script on the page after a server-side variable is assigned
" < script language='javascript' > var temp=" + tmp + " < /script > "
tmp is the background variable, and then js has direct access to temp to get the value.
An existing variable in C# that accesses JavaScript
Method 1:1. The foreground USES the static text control to hide the field and writes the js variable value into it.
2. The background USES request["id"] to get the value;
Method 2: you can use cookie or session
The JavaScript function is accessed in C#
Method 1:1, Page.RegisterStartupScript("ggg"," < script > SetVisible(1); < /script > ");
Method 2: use the Literal class, then
 
private void Button2_Click(object sender, System.EventArgs e) 
{ 
string str; 
str="<script language='javascript'>"; 
str+="selectRange()"; 
str+="</script>"; 
//Literal1.Visible=true; 
Literal1.Text=str; 
} 

Related articles: