Friday, May 04, 2007

Asp ImageButton/Button submits the page even though onClientClick javascript returns failure :(

Javascript function should actually make event.returnValue = false; and not return failure or -1
NOTE: Since this blog will not let me key in script tags, _ is prefixed ;)

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

<_asp:button id="btnAddChoice" runat="server" text="Add" onclientclick="AddToListBox(lbxChoices, txtChoiceName);">
as
<_input type="submit" name="btnAddChoice" value="Add" onclick="AddToListBox(lbxChoices, txtChoiceName);">

So when I click on the button, my JavaScript fires correctly but the page then submits -not what I want it to do. Thinking fast, I added a snippet to return false after my client-script ran, like so:

<_input type="submit" name="btnAddChoice" value="Add" onclick="AddToListBox(lbxChoices, txtChoiceName);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?What I do not want to to is capture it just before it renders and change it there. And I also do not want to try to manipulate the type attribute after it's already been rendered. The solution I found; .NET has a added an attribute (boolean) to the Button WebControl called UseSubmitBehavior. By setting it to false in the WebControl, like so:

<_asp:button id="btnAddChoice" runat="server" text="Add" onclientclick="AddToListBox(lbxChoices, txtChoiceName); return false;" usesubmitbehavior="false">

Renders the input control like I want it to, as a button:
<_input type="button" name="btnAddChoice" value="Add" onclick="AddToListBox(lbxChoices, txtChoiceName); return false;__doPostBack('btnAddChoice','')">
Notice that I still need to stop the execution of the JavaScript by returning false because .NET added __doPostBack('btnAddChoice','') 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.

Reference: http://www.xerratus.com/CommentView,guid,5a3ee461-185b-4253-9f98-2a9254208b15.aspx#commentstart


No comments: