Ryan Smith
Ryan Smith

Reputation: 8334

Canceling the default submit button in ASP.NET

I have an ASP.NET application where there's a few ASP.NET buttons and several plain HTML buttons. Anytime there's a textbox where a user hits enter, the ASP.NET button tries to submit the form.

I know I can change the defaultButton, but I don't want there to be any default button. I just want it so when the user presses enter it doesn't do anything.

I've tried setting defaultButton to blank, but that doesn't seem to work. How do I prevent the form from being submitted by the ASP.NET button when enter is pressed?

Upvotes: 21

Views: 21619

Answers (5)

Bill Mitchell
Bill Mitchell

Reputation: 1

I was getting an error when navigating to another page after having set my login form's Sign In button as the default as described above. My fix was to test in the Master Page's load event and if the contained page was not my login page, to set the default back to nothing like this:

if (Page.AppRelativeVirtualPath != "~/Login.aspx") {
    Page.Form.DefaultButton = "";
}

Upvotes: 0

David
David

Reputation: 73594

You can set the button's UseSubmitBehavior = false

btnCategory.UseSubmitBehavior = false;

Upvotes: 36

Thys
Thys

Reputation: 149

I also had this problem with an ImageButton on my MasterPage (the Logout button) being set as the default button (so whenever someone pressed Enter, it would log them out). I solved it by using the following line in the Page_Load event on every child page, which is a bit of a work-around, but it works:

Form.DefaultButton = cmdSubmit.UniqueID;

Hope this helps someone else.

Upvotes: 1

Biju NB
Biju NB

Reputation: 1

<asp:TextBox ID="TXT_Quality" runat="server" Width="257px" 
onkeypress="return key_Pressed(event, this);">
</asp:TextBox>   

function key_Pressed(e, textarea)
 {
    var code = (e.keyCode ? e.keyCode : e.which);
    if(code == 13) 
    { 
       return false;
    }
    return true;
 }

Upvotes: 0

Bryan Legend
Bryan Legend

Reputation: 6896

Here is what I used to fix this problem.

<form runat="server" defaultbutton="DoNothing">
        <asp:Button ID="DoNothing" runat="server" Enabled="false" style="display: none;" />

Upvotes: 26

Related Questions