Saturday, September 20, 2008

Asp.Net: Problem with the OnClientClick event of a Button Web Control

While working an ASP.NET 2.0 project today I ran across a problem with the OnClientClick event within the Button Web Control. The problem is that .NET renders this button:

<asp:Button ID="btnSave" runat="server" Text="Save & close" OnClientClick="Update ();" />
as

<input type="submit" name="btnSave" value="Save & close" onclick=" Update();" />


So when I click on the button, my JavaScript fires correctly but the page then submits – so to control this I added return false after my client-script ran, like so:

<input type="submit" name="btnSave" value="Save & close" onclick=" Update();return false;" />


This however, does not work; the page still submits. After looking at the rendered HTML I can see the problem right away -the button type is submit. What I need is for it to be a type of button.

An input control of type button, will not automatically submit the form. But how do I get .NET to render one?
The solution I found was in .NET there is an attribute (boolean) to the Button WebControl called UseSubmitBehavior. By setting it to false in the WebControl, like so:

<asp:Button ID="btnSave" runat="server" Text="Save & close" OnClientClick=" Update(); return false;" UseSubmitBehavior="false" />


Renders the input control like I want it to, as a button:

<input type="button" name="btnSave" value="Add" onclick=" Update(); return false;__doPostBack(‘btnSave’,'')" />


Notice that I still need to stop the execution of the JavaScript by returning false because .NET added __doPostBack(‘btnSave’,'') to the onclick event.

But the main difference is that by returning false the page DOES NOT submit. Now, I can go back to writing my client-script to manipulate the page and capture those changes when the real submit button is clicked and the server code takes over.

Post a Comment(0 comments)

0 Comments:

Post a Comment

<< Home