Scott Scowden
Scott Scowden

Reputation: 1195

Add ServerClick event to ASP.NET <button> element

I am looking to handle the click event of an HTML <button> (not an <input type="button">) on the back end. The reason I want to handle a button is because the design I have has button controls all over the place, so to modify all of the CSS would be much more work.

For my button, I have:

   <button type="submit" id="submit" runat="server">Send</button>

In my code behind, I have:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            submit.ServerClick += new EventHandler(submit_click);
        }
    }

    protected void submit_click(object sender, EventArgs e)
    {
        // never being hit
    }

Is this possible?

Upvotes: 2

Views: 5179

Answers (2)

Armstrongest
Armstrongest

Reputation: 15409

Another way is to just add it to the button element:

<button type="submit" id="submit" runat="server" onserverclick="Button1_OnClick">Send</button>

void Button1_OnClick(object Source, EventArgs e) 
  {
     // Do Something here
  }

http://msdn.microsoft.com/en-us/library/a8fd2268%28v=VS.100%29.aspx

Upvotes: 3

marcind
marcind

Reputation: 53183

You should remove the conditional check for if (Page.IsPostBack). Your code will not currently work because the onclick handler only gets set when the page gets first rendered. Then when the user clicks on the button a postback occurs but now your page code no longer has the handler associated with the button so there is no code to execute. Just do this:

protected void Page_Load(object sender, EventArgs e)
{
    submit.ServerClick += new EventHandler(submit_click);
}

protected void submit_click(object sender, EventArgs e)
{
    // now it should get hit
}

Upvotes: 3

Related Questions