0

我正在进行服务器端验证,但似乎它没有按应有的方式工作。下面是示例代码

     //Validation

    private void validation()
    {
        if (txtFName.Text == string.Empty) { Alert("Invalid Name"); return; }

        if (txtLName.Text == string.Empty) { Alert("Invalid Name"); return; }
    }


       // Alert mesage
  public void Alert(string msg)
    {
        ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script
         type='text/javascript'>alert('" + msg + "');</script>");
    }

在我的按钮下一次点击事件中,我正在调用这个函数

    protected void button_Click(object sender, EventArgs e)
    {
        validation();
    }

令人惊讶的是,即使我没有在 texbox 中输入任何内容(意味着文本框是空的)......没有警报到来。然而,它应该发出警报。

有人可以指出我做错了什么。感谢你的帮助。

编辑:

最奇怪的是,相同的代码在其他页面上也能正常工作。如果字段为空或验证失败,它会发出警报。不知道这个页面有什么问题。

Fe 指针……这个特殊的 aspx 页面……有很多用户控件,而这些控件 ascx 页面有 Javascript。我这可能是任何问题

4

3 回答 3

0

我刚刚尝试了以下代码。

protected void Button1_Click(object sender, EventArgs e)
{
    validation();
}

private void validation() 
{ 
    Alert("Invalid Name"); 
} 


   // Alert mesage 
public void Alert(string msg) 
{ 
    ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('" + msg + "');</script>"); 
} 

似乎一切正常。看看这个看看是否有任何设置问题。(不确定我只是在反复试验)。

http://bytes.com/topic/asp-net/answers/518330-clientscript-registerstartupscript

于 2012-01-25T01:14:22.517 回答
0

即使Scriptmanager没有成功... o,我的解决方案是...我只是稍微更改了验证方法,结果很好...如下所示

private bool validation() 
{ 
    if (txtFName.Text == string.Empty) { Alert("Invalid Name"); return false; } 

    if (txtLName.Text == string.Empty) { Alert("Invalid Name"); return false; } 
} 
于 2012-02-02T16:31:38.523 回答
0

我建议您使用 Asp.net 验证控件,例如必填字段验证器、比较验证器。因为框架会为你做所有的事情。那你为什么要自己验证。?

在 aspx 中

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="InvalidName" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>

如果您想在消息框或摘要中显示所有验证,您可以使用验证摘要控件

<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True" />
于 2012-01-25T01:25:06.153 回答