简体   繁体   中英

how to capture and fire a custom event for a user control on postback

I have a user control (eg foo.ascx) that doesn't use any asp.net controls. I don't have a button click event or anything I can depend on. So the following isn't an option:

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
}

I need to fire an ItemSelectedEvent. I know how to make the methods and events like so

public event EventHandler<MyEventArgs> ItemSelected;

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

What javascript do I need on the client site to indicate i'm firing the ItemSelected event (ie how to post back to the server correctly), and what do I need to implement in the code behind page to capture that information and call my OnItemSelected method?

If I am correct and you are using ASP.NET WebForm then you need to implement IPostBackEventHandler interface for your user Control. This interface defines the method(RaisePostBackEvent) which ASP.NET server controls must implement to handle postback events.

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

Then on client side you will able to execute server side event by invoking the following code:

__doPostBack(UniqueID, 'eventArgument');

where UniqueID - Unique ID of your user control. eventArgument can be empty or any value what you want (for example object in json format and etc).

This is how server side postback events can be implemented for custom server control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM