Asp.NET html <button> element onclick and onserverclick -> client-side validation

The problem solved here is that an <button> element (html = <button runat=”server” > or <asp:HtmlButton )  doesn’t support a onclientclick event. This prevents performing client side validation ahead of the onserverclick event.

Here’s more on the problem.

The solution proposed in the stackoverflow discussion above won’t work is the <button> is inside a <form> tag. This is because, while the button won’t do the _postBack it will act as an <input type=”submit” /> and submit the form when clicked. Far from ideal, the button is still active in some unpredictable way.

The (hacky) solution I’ve come up with is to, using jQuery,

  1. Save the ‘onserverclick’ attribute value when the dom loads.
  2. Remove the now saved ‘onserverclick’.
  3. Add a click listener using jQuery (for validation)
  4. In the validation, return false always (prevents from submit, no effect on _postBack).
  5. If however the validation is good, ‘eval()’ the post back. I.e. execute the onclick event programmatically using (some sort of) reflection. Return false to prevent the <button> submitting the form.


Here’s a worked example:



Comments welcome……



  • Gorky

    awesome, this is exactly was I looking for, thank you. I have to put the attribute clientidmode=”Static” in the control to preserve its id and the jquery selector works properly, beside that excellent post