Search code examples
c#javascriptjqueryasp.net-ajaxmouseclick-event

Registering asp:button click event handler


I have multiple asp:button that I created dynamically with jQuery.

For each of them, I have OnClick="ibtn_Click" .

But on the code behind, I have to manually register each one of them on Page_Load..like.. button.Click += new EventHandler(this.ibtn_Click); .

Is there a way I can register this handler automatically? Or is it possible to register it with ajax jquery?

Thanks!


Solution

  • You can't add ASP.NET web controls in the client's browser. ASP.NET transforms those <asp:button> tags into regular HTML, something like this:

    <input type="submit" name="Button1" value="Ok" id="Button1" />
    

    When a user clicks one of these submit controls, the browser sends a POST request, which includes the button's name as part of the posted data (which you can access via the Form collection in ASP.NET):

    if (this.IsPostBack && Request.Form["Button1"] != null) {
        // do something if the user clicked Button1
    }
    

    ASP.NET automatically binds server control clicks to the methods specified in the OnClick attribute. It calls the method after Page.Load completes (for the gory details, see "ASP.NET Page Life Cycle Overview").

    If you're adding the buttons on the client, you can do all this yourself. For example you could "bind" the dynamically generated button in Page_PreRender:

    protected void Page_PreRender(object sender, EventArgs e) {
        if (this.IsPostBack && Request.Form["Button1"] != null) {
            // Call another method on the page
        }
    }
    

    Finally, in this day and age, if it's appropriate, you should definitely consider just calling page methods via jQuery's ajax. See this excellent Encosia article for an introduction to that technique.