Skip to main content
 首页 » 编程设计

c#之如何在回发时为用户控件捕获和触发自定义事件

2024年02月13日13bhlsheji

我有一个不使用任何 asp.net 控件的用户控件(例如 foo.ascx)。我没有按钮点击事件或任何我可以依赖的东西。所以以下不是一个选项:

void Page_Load(object sender, EventArgs e) { 
  MyButton.Click += MyButton_Click; // <-- I can't do this, there are no asp.net controls 
} 
 
void MyButton_Click(object sender, EventArgs e) { 
    OnItemSelected("foo"); // fire my custom event 
} 

我需要触发一个 ItemSelectedEvent。我知道如何制作这样的方法和事件

public event EventHandler<MyEventArgs> ItemSelected; 
 
void OnItemSelected(string selectedItem) { 
  var tmp = ItemSelected; 
  if (tmp != null) 
    tmp(this, new MyEventArgs { SelectedItem = selectedItem }); 
} 

我需要在客户端站点上使用什么 javascript 来指示我正在触发 ItemSelected 事件(即如何正确回发到服务器),以及我需要在代码中实现什么在页面后面捕获该信息并调用我的 OnItemSelected 方法?

请您参考如下方法:

如果我是正确的并且您正在使用 ASP.NET WebForm,那么您需要实现 IPostBackEventHandler用户控件的界面。该接口(interface)定义了 ASP.NET 服务器控件必须实现以处理回发事件的方法 (RaisePostBackEvent)。

  // Define the method of IPostBackEventHandler that raises your server side events.  
  public void RaisePostBackEvent(string eventArgument){ 
     OnItemSelected("foo"); // fire my custom event 
  } 

然后在客户端,您将能够通过调用以下代码来执行服务器端事件:

__doPostBack(UniqueID, 'eventArgument'); 

其中 UniqueID - 您的用户控件的唯一 ID。 eventArgument 可以为空或您想要的任何值(例如 json 格式的对象等)。

这是为自定义服务器控件实现服务器端回发事件的方式。