![](/img/trans.png)
[英]How To Make A Web User Control's Child Control's Events Cause A Catchall Event To Fire On The Parent Once Per Postback
[英]how to capture and fire a custom event for a user control on postback
我有一個不使用任何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,那么您需要為您的用戶Control實現IPostBackEventHandler接口。 此接口定義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格式的對象等)。
這是為自定義服務器控件實現服務器端回發事件的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.