/**************************************************************************/
//
//ASP.NET回调(Callback)环境的搭建
//资料来源:自己整理
/**************************************************************************/
使用ASP.NET控件来执行函数的时候,页面必须经过重新加载才能显示更新后的内容。
如果页面刷新会带来很多的麻烦,比如:会加重网络传输的负担、页面的不连贯的现实会给用户带来很不友好效果。
这里主要实现:通过前台的HTML控件调用JavaScript脚本,然后将相关的参数传入到后台,经过后台处理后,然后将结果以字符串的形式传到前台,然后显示处理的结果。
在这个整个过程中,页面仅仅需要刷新部分内容而不用刷新整个页面,这样整个页面也就不用重新加载了。
主要的操作:
向页面添加一个HTML按钮,然后给他添加一个click函数,函数的内容如下所示:
/**********************************************************************/
//前台代码
/**********************************************************************/
//前台HTML控件
<input type="button" value="Get Server Time" onclick="getServerTime();" />
<div id="timeLabel"></div>
//JavaScript脚本
<script language="javascript" type="text/javascript">
//按钮调用的函数 getServerTime()
function getServerTime()
{
//context、message、CustomCallbackFunctionString 为回调函数必须的内容。这个函数的格式就是和下面的是一样的
var context = 'Page1';
var message = 'getServerTime';
<%=CustomCallbackFunctionString%>
}
//定义处理回调结果的函数:processMyResult,回调的结果是字符串的
function processMyResult(callbackResult, context)
{
var timeDiv = document.getElementById('timeLabel');
//将回调结果写入到HTML的DIV标签内部
timeDiv.innerHTML = callbackResult;
}
//处理回调结果报错情况,回调结果是将错误信息弹出
function postMyError(callbackResult, context)
{
alert("Callback Error: " + callbackResult + ", " + context);
}
</script>
/**********************************************************************/
//后台的代码
//说明:后面有***的表示是回调处理所必须函数
/**********************************************************************/
public partial class SimpleCallback : System.Web.UI.Page, System.Web.UI.IcallbackEventHandler
// 这里我们需要继承System.Web.UI.IcallbackEventHandler ***
{
private string m_CustomCallbackFunctionString;//***
private string m_CallbackResults;//***
protected void Page_Load(object sender, System.EventArgs e)
{
m_CustomCallbackFunctionString = Page.ClientScript.GetCallbackEventReference(this, "message", "processMyResult", "context", "postMyError", true);//***
// message 传入到后台的参数
//processMyResult 为前台处理回调结果的JavaScript函数
//context 为一个字符串,具体的作用我也不是很理解
//postMyError 如果回调发生错误,那么就有这个参数来进行处理
}
public void RaiseCallbackEvent(string eventArgument)
{
//根据传入的参数的判断来调用后台响应的代码
if (eventArgument == "getServerTime")// getServerTime 就是从前台传入的参数,Page_Load函数中的message代表他。
{
m_CallbackResults = System.DateTime.Now.ToString();//后台处理回调函数
}
}
//
public string GetCallbackResult()//这个函数是必须的。具体的作用我也不知道是什么。 ***
{
//将返回的结果返回到前台
return m_CallbackResults;
}
//
public string CustomCallbackFunctionString //*** 这个函数是必须的
{
get
{
return m_CustomCallbackFunctionString;
}
set
{
m_CustomCallbackFunctionString = value;
}
}
}