ASP.Net page enter key causing post back

前端 未结 6 418
眼角桃花
眼角桃花 2020-12-02 23:40

I have an aspx page that postsback when it should not. there are two text boxes, two listboxes and two buttons on the page. if at any-point the enter key is pressed the firs

相关标签:
6条回答
  • 2020-12-02 23:44
    • You could set the DefaultButton on the Form or a Panel. This way you have full control what happens.
    • Set UseSubmitBehavior="False" on your Buttons. This disables the "AutoPostback" on Enter.

    I would prefer the second if i wanted to prevent Postbacks on Enter completely.

    0 讨论(0)
  • 2020-12-02 23:53

    Only put this on you ASP.Net TextBox control:

    <asp:TextBox ID="TextBox1" runat="server"
       onkeydown = "return (event.keyCode!=13);" >
    </asp:TextBox>
    
    0 讨论(0)
  • 2020-12-02 23:56

    Use the below code to disable enter key causing postback. This piece of code will block the enter key in all browsers 4.0 above, except when enter is pressed in a Textarea or on the Submit button itself.

    <script language="JavaScript">
    var nav = window.Event ? true : false;
    if (nav) {
    window.captureEvents(Event.KEYDOWN);
    window.onkeydown = NetscapeEventHandler_KeyDown;
    } else {
    document.onkeydown = MicrosoftEventHandler_KeyDown;
    }
    
    function NetscapeEventHandler_KeyDown(e) {
    if (e.which == 13 && e.target.type != 'textarea' && e.target.type != 'submit') { 
    return false; 
    }
    return true;
    }
    
    function MicrosoftEventHandler_KeyDown() {
    if (event.keyCode == 13 && event.srcElement.type != 'textarea' && 
    event.srcElement.type!= 'submit')
    return false;
    return true;
    }
    </script>
    
    0 讨论(0)
  • 2020-12-02 23:57
    <body onkeydown = "return (event.keyCode!=13)">
    
    0 讨论(0)
  • 2020-12-03 00:00

    are you using jQuery?

    if so:

    $(document).keypress(function(e)
    {
        if(e.keyCode === 13)
        {
            e.preventDefault();
            return false;
        }
    });
    
    0 讨论(0)
  • 2020-12-03 00:08

    This is default behavior of a web application, you could take one of the tutorials that you found and hide that behavior, by simply abandoning the submit.

    0 讨论(0)
提交回复
热议问题