首先新建一網站項目,並在default.ASPx.cs添加System.Web.UI.ICallbackEventHandler接口。
再為整個頁面類添加如下函數:
public void RaiseCallbackEvent(string eventArgument)
{
}
個人理解:在服務器處理前可以對客戶端傳遞參數進行判斷處理。
public string GetCallbackResult()
{
}
個人理解:服務器端處理函數
備注:實現
ICallbackEventHandler 接口的控件的示例包括 GridView、DetailsView 和 TreeVIEw 控件。當回調事件以實現了
ICallbackEventHandler 接口的控件為目標時,將把事件變量作為參數傳遞來調用 RaiseCallbackEvent方法以處理該事件,並且 GetCallbackResult方法返回回調的結果。
發送回調函數:
String cbReference =Page.ClIEntScript.GetCallbackEventReference(this, "arg",
"ReceiveServerData", "context");
ReceiveServerData
9pt">為客戶端回調函數
function ReceiveServerData(rvalue, context)
{
document.getElementById("main").innerText = "Return value = "+rvalue;//顯示
}
個人理解:arg為客戶端傳向服務器端參數,而context為客戶端回傳客戶端參數,在服務器端不進行變化
將上面封裝成事件函數:
String callbackScript = "function CallServer(arg, context) {" +
cbReference + "; }";
Page.ClientScript.RegisterClIEntScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
將函數賦給控件:
this.Button1.Attributes.Add("onclick", "CallServer('','')");
操作實例:
以下實例源碼提供:
Default.ASP
<%@ Page Language="C#" AutoEventWireup="true" CodeFile
: blue">="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>CallBack機制</title>
<script type="text/Javascript">
function ReceiveServerData(rvalue,context)
{
if(context=="1")
{
document.getElementById("main").innerText = "Return value = "+rvalue+context;
}
else
{
document.getElementById("main1").innerText = "Return = "+rvalue+context;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="加—" runat="server"/>
<>input id="Button2" type="button" value="加—>>" runat="server"/></div>
<div id="main">ss</div>
<div id="main1">ss</div>
</form>
</body>
</Html>
Default.ASPx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
LOR: blue">using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
String cbReference =Page.ClIEntScript.GetCallbackEventReference(this, "arg",
"ReceiveServerData", "context");
String callbackScript = "function CallServer(arg, context) {" +
cbReference + "; }";
Page.ClientScript.RegisterClIEntScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
this.Button1.Attributes.Add("onclick", "CallServer('1','1')");
this.Button2.Attributes.Add("onclick", "CallServer('2','2')");
}
string returnValue;
public void RaiseCallbackEvent(string eventArgument)
{
if (eventArgument == "2")
{
returnValue = ">>";
}
}
public string GetCallbackResult()
t"> {
string str = "";
int k = 0;
for (int i = 1; i < 10; i++)
{
k= i * 2;
str += k.ToString()+"—"+returnValue;
}
return str;
}
}