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

The problem solved here is that an asp.net <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.

http://stackoverflow.com/questions/1245033/asp-net-onserverclick-event-handler-not-called-if-using-onclick

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.

Confused?

Here’s a worked example:

 

 

Comments welcome……

 

 

1 Comment

  • 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