rattrick1 rattrick1 - 12 days ago 4
ASP.NET (C#) Question

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?

Answer

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
}
Comments