ASP.NET:ListView中具有多个TextBox的RequiredFieldValidator

时间:2012-11-05 20:11:55

标签: asp.net listview controls requiredfieldvalidator

我有一个ListView

<asp:ListView ....>
    <asp:TextBox ID="txtComment" ... />
    <asp:RequiredFieldValidator ID="rfvComment" ControlToValidate="txtComment" ... />
    <act:ValidatorCalloutExtender ID="vceComment" TargetControlID="rfvComment" ... />

    <asp:Button ID="btnAddComment" ... />

</asp:ListView>

让我们说这个ListView创建了以下内容:

TextBox1中 按钮1

TextBox2中 BUTTON2

TextBox3 BUTTON3

如果我单击Button2,则RequiredFiledValidator / ValidatorCalloutExtender应用于TextBox1而不是TextBox2,如果我单击Button3,RequiredFiledValidator / ValidatorCalloutExtender也会应用于TextBox1,我希望RequiredFiledValidator / ValidatorCalloutExtender应用于旁边的TextBox按钮,所以如果我单击Button3,我希望它应用于TextBox3。

有谁知道我怎么能实现这个目标?

谢谢。

2 个答案:

答案 0 :(得分:4)

使用ValidationGroup属性并动态生成它:

<asp:TextBox runat="server" ID="TextBox1" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="TextBox1" Text="*"
    ValidationGroup='<%# "validationGroup_" + Container.DataItemIndex.ToString() %>' />
<asp:Button runat="server" Text="Click Me" ValidationGroup='<%# "validationGroup_" + Container.DataItemIndex.ToString() %>' />

在表格的最底部添加以下脚本:

<script type="text/javascript">
    var originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
    ValidatorUpdateDisplay = function (val) {
        originalValidatorUpdateDisplay.call(null, val);
        var isHidden = val.style.display == "none" || val.style.visibility == "hidden";

        var extender = Sys.UI.Behavior.getBehaviorsByType(val, Sys.Extended.UI.ValidatorCalloutBehavior);
        if (extender && extender.length == 1) {
            extender = extender[0];
            if (isHidden) {
                extender.hide();
            }
            else {
                extender.show(true);
            }
        }
    }
</script>

我想自定义工具包源会更好,但我没心情这样做:)所以希望这个脚本能解决你的问题

答案 1 :(得分:0)

尝试smth(例如,应该有用)

<asp:Panel ID="registration" defaultbutton="regButton" runat="server">

<asp:TextBox ID="name" Rows="1" CssClass="text" runat="server" ValidationGroup="Registration">
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Enter your name please" Text="*" ControlToValidate="name"  EnableClientScript="False" Display="Dynamic" ValidationGroup="Registration" />


<asp:TextBox ID="address" Rows="1" CssClass="text" runat="server" ValidationGroup="Registration"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Enter your address please" Text="*" ControlToValidate="address"  EnableClientScript="False" Display="Dynamic" ValidationGroup="Registration" />


<asp:ValidationSummary DisplayMode="BulletList" EnableClientScript="false" ID="validation_sum" runat="server"  HeaderText="Errors list"  ValidationGroup="Registration"/>


<asp:Button runat="server" id="regButton" Text="Register please" ValidationGroup="Registration" OnClick="RegisterUser"/>

</asp:Panel>