ASP .NET:CustomValidator不会启动其ServerValidate方法

时间:2013-01-26 10:37:27

标签: c# asp.net .net

aspx代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyWebForm.aspx.cs" Inherits="MyWebApplication.MyWebForm" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body style="height: 334px">
    <form id="form1" runat="server">
    <div style="height: 338px">

        <asp:TextBox ID="MyTextBox" runat="server" AutoPostBack="True"></asp:TextBox>
        <br />
        <asp:CustomValidator ID="MyCustomValidator" runat="server" 
            ControlToValidate="MyTextBox" ErrorMessage="My error message" 
            onservervalidate="Foo2"></asp:CustomValidator>

    </div>
    </form>
</body>
</html>

C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyWebApplication
{
    public partial class MyWebForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        bool Foo1(string bar)
        {
            if (bar == "bar")
                return true;
            return false;
        }

        protected void Foo2(object source, ServerValidateEventArgs args)
        {
            args.IsValid = this.Foo1(this.MyTextBox.Text);
        } // breakpoint
    }
}

我在Foo2函数(注释)中设置了断点,但是调试器没有访问它。我尝试编写不同的文本,没有写任何东西并写入“bar”并在之后按下enter和tab,但它仍然无效。我的意思是文字改变动作。有可能吗?

1 个答案:

答案 0 :(得分:3)

没有提交按钮。您需要添加一个按钮来提交表单,然后触发页面验证。

<asp:Button runat="server" id="myButton" Text="Submit" />