关闭

解决AjaxControlToolkit中ComboBox不能验证的问题

1233人阅读 评论(0) 收藏 举报

原因从官网上得知,ComboBox是TextBox与其它控件的一个组合控件,因此如果直接绑定验证的话,验证控件将不会直接指向TextBox,因此只能使用CustomValidator 控件,但是在CustomValidator 控件的JS中,需要通过使用$find函数找到ComboBox当前的对象,然后再使用对像的_textBoxControl属性找到TextBox,代码如下所示

C# Code:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var data = new[] { new { Id = 0, Name = "Jim.Yu" }, new { Id = 1, Name = "Simon.Fan" }, new { Id = 2, Name = "Allen.Zhao" } };
                this.ComboBox1.DataTextField = "Name";
                this.ComboBox1.DataValueField = "Id";
                ComboBox1.DataSource = data;
                ComboBox1.DataBind();
            }
        }

 

ASPX:

<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <cc1:ComboBox ID="ComboBox1" runat="server">
        </cc1:ComboBox>
        <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="ComboBox1"
            ValidateEmptyText="true" ClientValidationFunction="CustomValidator" Display="Dynamic"
            ErrorMessage="Custom Validator"></asp:CustomValidator>
        <br />
        <br />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ControlToValidate="TextBox1" Display="Dynamic"
            ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" />
                <script language="javascript">
                    function CustomValidator(s, e) {
                        if ($find(s.controltovalidate)._textBoxControl.value == "") {
                            e.IsValid = false;
                        }
                    }
        </script>

0
0

猜你在找
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4528次
    • 积分:99
    • 等级:
    • 排名:千里之外
    • 原创:5篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章存档