除了利用AJAX框架之外,我们可以通过在页面实现ICallbackEventHandler接口实现客户端与服务器的异步通讯。下面我们实现如下一个简单的例子:当点击按钮时将文本框中的数值送到服务器,然后服务器处理该字符串值并传回客户端,在客户端弹出提示框显示,整个过程异步完成。
ICallbackEventHandler接口包含两个方法:
1. RaiseCallbackEvent:被客户端触发的服务器端事件,接受来自客户端的参数eventArgument;
2. GetCallbackResult:将服务器端处理结果返回给客户端。
该实现方式的重点为建立起客户端控件与服务器端事件的关联,代码中通过callServer和receiveServerResult两个javascript脚本建立起客户端与服务器端的联系,并借助GetCallbackEventReference方法实现返送的脚本。
前台页面代码
...
<script type="text/javascript">
function callServer(arg){
var oTb = document.getElementById('<%=editValue.ClientID %>');
arg = oTb.value;
<%=ClientScript.GetCallbackEventReference(this, "arg", "receiveServerResult", null, true)%>
}
function receiveServerResult(result){
// 在这里添加处理服务器返回结果的逻辑,result变量是服务器返回的结果
alert(result);
}
</script>
...
<asp:TextBox ID="editValue" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit Data" UseSubmitBehavior="false" OnClientClick="callServer();return false;" />
...![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
...
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
...
![](/Images/OutliningIndicators/None.gif)
后台文件代码
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ContractedSubBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
相关链接:
ICallbackEventHandler
GetCallbackEventReference