当UseSubmitBehavior =“false”但文本框值为空时,按钮未正常触发并触发

时间:2011-03-07 13:25:41

标签: javascript asp.net

我正在使用ASP按钮,它在客户端正常工作,但在服务器端却没有触发。

<div style="text-align: center">
    <div>
        <div id="UserName">
            <b>LoginName</b>
            <asp:TextBox ID="txt_LoginName" runat="server"></asp:TextBox>
        </div>
    </div>
    <div>
         <div id="Password">
             <b>Password&nbsp;&nbsp;</b>
             <asp:TextBox ID="txt_Password" TextMode="Password" runat="server"></asp:TextBox>
         </div>
    </div>
    <div style="text-align: right; width: 210px;">
        <asp:Button ID="btn_SignIn" OnClientClick="LogInUser()" UseSubmitBehavior="false" runat="server" Text="Login`enter code here`" />
        <asp:Label ID="lbl_InValidError" runat="server"></asp:Label>
    </div>
</div> 

客户端代码:

    function LogInUser()
    {
        var LoginName = document.getElementById("<%=txt_LoginName.ClientId %>").value;
        var Password = document.getElementById("<%=txt_Password.ClientId%>").value;

        if(LoginName == '')
        {
            alert("Please Enter UserName.");
            return false;
        }
        else
        {
            if(Password == '')
            {
                alert("Please Enter Password.");
                return false;
            }
            else
            {
                alert("You are logged in");                   
            }
        }
        return true;
    }

服务器端代码

Protected Sub btn_SignIn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_SignIn.Click
 If Trim(Me.txt_LoginName.Text) = "" Then
            lbl_InValidError.Text = "Please Enter Login Name."
            Return
        End If
        If txt_Password.Text = "" Then
            lbl_InValidError.Text = "Please Enter Password."
            Return
        End If
End Sub

当我不使用UseSubmitBehavior=false事件时,服务器端不会发生火灾。

1 个答案:

答案 0 :(得分:0)

将OnClientClick更改为:

OnClientClick="if (LogInUser() == false) return;"

这样,如果用户未经过验证,则会阻止回发,但如果有效,则允许用户继续回传。