65.9K
CodeProject 正在变化。 阅读更多。
Home

ICallbackEventHandler

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2013 年 10 月 11 日

CPOL
viewsIcon

9867

通过使用 ICallbackEventHandler,我们可以向服务器发起异步调用,从而避免网页回发。首先,我们需要实现

通过使用 ICallbackEventHandler,我们可以向服务器发起异步调用,从而避免网页回发。

首先,我们需要实现 ICallbackEventHandler 接口,
public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
然后,我们需要在 ICallbackEventHandler 接口中实现两个方法,
  • GetCallbackResult
  • RaiseCallbackEvent
  #region ICallbackEventHandler Members

public string GetCallbackResult()
{return result;}
public void RaiseCallbackEvent(string eventArgument)
{
result = "Call Back Result";
}

#endregion
为了简单起见,这里我返回静态数据。你也可以返回动态数据。然后,你需要通过 Page.ClientScript 获取回调事件引用,
string callback = ClientScript.GetCallbackEventReference(this, "arg", "GetName", "context");
string script = "function CallBack(arg,context){" + callback + ";}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "CB", script, true);
所以现在我们的类看起来像这样,
using System;
using System.Configuration;
using System.Data;
using System.Linq;
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.Xml.Linq;

public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{
public string result;
protected void Page_Load(object sender, EventArgs e)
{
string callback = ClientScript.GetCallbackEventReference(this, "arg", "GetName", "context");
string script = "function CallBack(arg,context){" + callback + ";}";
ClientScript.RegisterClientScriptBlock(this.GetType(), "CB", script, true);
}

#region ICallbackEventHandler Members
public string GetCallbackResult()
{
return result;
}

public void RaiseCallbackEvent(string eventArgument)
{
result = "Call Back Result";
}
#endregion
}
现在在设计器中添加一个文本框和一个 HTML 按钮。为了回调,我们应该使用 HTML 按钮。在 HTML 按钮的 onclick 事件中调用 javascript 方法 GetValue();

我们的 Javascript 代码如下所示,
  function GetValue()
{
CallBack();
}
function GetName(arg,context)
{
document.getElementById('txtPercentage').value=arg;
}
构建并运行应用程序。现在,单击 HTML 按钮时,文本框将从服务器填充值,而无需发布页面。
© . All rights reserved.