我有一个不使用任何 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 格式的对象等)。
这就是为自定义服务器控件实现服务器端回发事件的方式。
关于c# - 如何在回发时捕获并触发用户控件的自定义事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19059169/