Xerratus
Happily stressed out, since 1974


 
Tuesday, November 21, 2006
<< AH HAH... Found it!
Setting a cell to NULL when editing data in SQL within a tableview >>

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.