Asp.net callback technique Callback study notes

  • 2021-01-02 21:48:14
  • OfStack

.aspx:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title> No title page </title> 

<script type="text/javascript"> 

// Pass parameters to the server  
function DoSearch(){ 
var firstName=document.getElementById("TextBox1").value; 
CallServer(firstName,""); 
} 

// Get the data from the server  
function ReceiveServerData(txtUserInfo){ 
Results.innerHTML=txtUserInfo; 
} 

// Set each 1 Seconds to perform 1 time  
setInterval("DoSearch()",1000); 
</script> 

</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
 The name :<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
<br /> 
<span id="Results" style=" width:500px;"></span> 
</div> 
</form> 
</body> 
</html>
[/code]
.aspx.cs
[code]
using System; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Data.SqlClient; 

public partial class _Default : System.Web.UI.Page, ICallbackEventHandler 
{ 
protected string txtUserInfo; 


protected void Page_Load(object sender, EventArgs e) 
{ 
// To obtain 1 A reference to a client function  
string cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context"); 
// Dynamically registers callback functions  
string callbackScript = "function CallServer(arg,context)" + "{" + cbReference + "};"; 
// trigger callbackScript 
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallServer", callbackScript, true); 
} 

// trigger Callback The event processing  
public void RaiseCallbackEvent(string txtFirstName) 
{ 
if (txtFirstName != null) 
{ 
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["sqlserver2008"].ToString(); 

SqlConnection conn = new SqlConnection(connString); 

conn.Open(); 

SqlCommand comm = new SqlCommand("select * from zzx where [name]=@name", conn); 

comm.Parameters.Add("@name", SqlDbType.VarChar).Value = txtFirstName; 

SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection); 
if (reader.Read()) 
{ 
txtUserInfo = " Employee number :" + reader["id"].ToString() + "<br>"; 
txtUserInfo += " Employee name :" + reader["name"].ToString() + "<br>"; 
txtUserInfo += " address :" + reader["address"].ToString() + "<br>"; 
txtUserInfo += " Server query time :" + DateTime.Now.ToString(); 
} 
else 
{ 
if (string.IsNullOrEmpty(txtFirstName)) 
{ 
txtUserInfo = " Please enter your name "; 
} 
else 
{ 
txtUserInfo = " No such person "; 
} 
} 

comm.Dispose(); 
reader.Dispose(); 
conn.Dispose(); 
} 
} 

// Get the result of the callback , Return to the client  
public string GetCallbackResult() 
{ 
return txtUserInfo; 
} 


}

Simplified version (lazy 1):


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title> No title page </title> 

<script type="text/javascript"> 
function OnCallBack(txtUserInfo,context){ 
Results.innerHTML=txtUserInfo; 
} 
</script> 

</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
 The name :<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
<input id="Button2" type="button" value="button" 
onclick="<%=Page.ClientScript.GetCallbackEventReference(this, "document.getElementById('TextBox1').value", "OnCallBack",null)%>" /> 
<br /> 
<span id="Results" style="pink; width: 500;"></span> 
</div> 
</form> 
</body> 
</html>
.aspx.cs

using System; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Data.SqlClient; 
using System.Text; 
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler 
{ 
protected StringBuilder txtUserInfo; 

protected void Page_Load(object sender, EventArgs e) 
{ 

} 

public string GetCallbackResult() 
{ 
return txtUserInfo.ToString(); 
} 

public void RaiseCallbackEvent(string txtFirstName) 
{ 
txtUserInfo = new StringBuilder(); 
String connString = ConfigurationManager.ConnectionStrings["sqlserver2008"].ToString(); 
SqlConnection conn = new SqlConnection(connString); 
conn.Open(); 
SqlCommand comm = new SqlCommand("select * from zzx where [name]=@name", conn); 
comm.Parameters.Add("@name", SqlDbType.VarChar).Value = txtFirstName; 
SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection); 
if (reader.Read()) 
{ 
txtUserInfo.Append(" Employee number :" + reader["id"].ToString() + "<br>"); 
txtUserInfo.Append(" Employee name :" + reader["name"].ToString() + "<br>"); 
txtUserInfo.Append(" address :" + reader["address"].ToString() + "<br>"); 
txtUserInfo.Append(" The query time :" + DateTime.Now.ToString()); 
} 
else 
{ 
if (txtFirstName == string.Empty) 
{ 
txtUserInfo.Append(" Please enter your name "); 
} 
else 
{ 
txtUserInfo.Append(" No such person "); 
} 
reader.Dispose(); 
comm.Dispose(); 
conn.Dispose(); 
}
} 
}

Example 3:


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title> No title page </title> 
<script type="text/javascript"> 
// Methods executed by the client  
// The following method receives and processes the results returned by the server method  
function Success(args,context){ 
message.innerHTML=args; 
} 

// The following method is called when an exception occurs to the result handled by the receiving server method  
function Error(){ 
message.innerHTML=" Something is wrong !"; 
} 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
 The user name :<input type="text" id="txtUserName" onblur="CallServerMethod(txtUserName.value,null)" /> 
<span id="message"></span> 
<br /> 
 password :<input type="password" size="10" maxlength="20" id="txtPwd" /> 
</div> 
</form> 
</body> 
</html>
[code]
public partial class Default3 : System.Web.UI.Page,ICallbackEventHandler // implementation ICallbackEventHandler interface  
{ 

String result = String.Empty; 

protected void Page_Load(object sender, EventArgs e) 
{ 
// Gets the current page of ClientScriptManager A reference to the  
ClientScriptManager csm = Page.ClientScript; 
/* Gets a reference to the callback . Will be generated on the client side WebForm_DoCallback methods , 
*  Call it to make an asynchronous call . This method is the method written by Microsoft , Will be sent  
 To the client */ 
/* Notice that the "Success" and Error The two strings are in the client code  
* Two definitions javascript function */ 
// The following method is final 1 The meaning of the parameters :true Means to perform an asynchronous callback ,false Flags perform a synchronous callback  
String reference = csm.GetCallbackEventReference(this, "args", "Success", "", "Error", true); 
String callbackScript = "function CallServerMethod(args,context){\n"+ 
reference+";\n }"; 
// Register with the current page javascript Script code  
csm.RegisterClientScriptBlock(this.GetType(), "CallServerMethod",callbackScript,true); 
} 

#region ICallbackEventHandler  Members of the  

/// <summary> 
///  A method that returns the result of a callback method execution  
/// </summary> 
public string GetCallbackResult() 
{ 
return result; 
} 

/// <summary> 
///  Run the callback method on the server side  
/// </summary> 
public void RaiseCallbackEvent(string eventArgument) 
{ 
if (eventArgument.ToLower().IndexOf("admin")!=-1) 
{ 
result =eventArgument+ " Cannot be registered as a user ."; 
} 
else 
{ 
result = eventArgument + " You can register ."; 
} 
} 

#endregion 
}

Related articles: