简体   繁体   English

groupname在转发器asp.net中的多个单选按钮中不起作用

[英]groupname doesn't work in more than one radiobutton inside repeater asp.net

I have a repeater and inside the repeater a radiobutton control, in code behind I fill the groupname for the radiobutton control, so, when I run it, I have a table with many rows and some of them have radiobutton: 我有一个转发器,在转发器内部有一个radiobutton控件,在后面的代码中我填充了radiobutton控件的groupname,因此,当我运行它时,我有一个包含许多行的表,其中一些有radiobutton:

  <asp:updatepanel id="UpdatePanel1" runat="server" updatemode="Conditional">
    <ContentTemplate>
        <asp:Repeater ID="Repeater1" runat="server" ViewStateMode="Enabled">
            <HeaderTemplate>
                <table class="table table-responsive table-bordered ">
                    <tr class="text-center" style="background-color: #6e6259; color: white;">
                        <th class="text-center">DESCRIPTION</th>
</HeaderTemplate>
            <ItemTemplate>
         <tr>
        <td style="padding-left: 20px;">
      <asp:RadioButton ID="rbtDinamic"  OnCheckedChanged="rbtDinamic_CheckedChanged" AutoPostBack="true"
           ViewStateMode="Enabled" Visible="false"  GroupName='<%#Eval("groupvalue") %>'   runat="server"/></td>
</ItemTemplate>
      <FooterTemplate>
    </table>
     </FooterTemplate>
    </asp:Repeater>
     </ContentTemplate>
      </asp:UpdatePanel>

And in the itemdatabound of repeater I fill the value for groupname: 在转发器的itemdatabound中,我填充groupname的值:

  Private Sub Repeater1_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles Repeater1.ItemDataBound
    Try
        If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
            If CType(e.Item.FindControl("hdf1"), Label).Text = False Then
                CType(e.Item.FindControl("rbtDinamic"), RadioButton).Visible = True
                CType(e.Item.FindControl("rbtDinamic"), RadioButton).GroupName = CType(e.Item.FindControl("groupvalue"), Label).Text = False
            End If
        End If
    Catch ex As Exception          
    End Try
End Sub

But when I run it the repeater creates the group name with diferent names: 但是当我运行它时,转发器会创建具有不同名称的组名:

Radiobutton row 1:
Repeater1$ctl05$1

Radiobutton row 2:

Repeater1$ctl06$1

So it let checked all the radiobuttons, instead to uncheck when another one for the same group is cheked. 所以它让我们检查所有的radiobuttons,而不是当同一组中的另一个被解雇时取消选中。

I find this code in a forum, but it work only if I have only one groupname, but I can have more than one groupname: 我在论坛中找到了这段代码,但只有当我只有一个组名时,它才有效,但我可以有多个组名:

  Protected Sub rbtDinamic_CheckedChanged(sender As Object, e As EventArgs)
    For Each item As RepeaterItem In Repeater1.Items
        Dim rbtn As RadioButton = DirectCast(item.FindControl("rbtDinamic"), RadioButton)
        rbtn.Checked = False
    Next
    DirectCast(sender, RadioButton).Checked = True
End Sub

But there can be more than one group of radiobuttons, so in this case I can't use this code. 但是可以有多组radiobuttons,所以在这种情况下我不能使用这个代码。

Is there anywhere to do this? 有没有可以做到这一点? thanks 谢谢

This is a known bug related with RadioButton control usage inside ItemTemplate or AlternatingItemTemplate ( more info ). 这是与ItemTemplateAlternatingItemTemplate RadioButton控件使用相关的已知错误( 更多信息 )。 This caused by Repeater mangling the naming of control ID & group names which assigned automatically in background (assumed using dynamic ClientIDMode ). 这是由Repeater破坏控制ID和组名称的命名,后者在后台自动分配(假设使用动态ClientIDMode )。 To fix this issue, set up a client-side function like this: 要解决此问题,请设置如下客户端功能:

function setExclusiveRadioButton(name, current)
{
    regex = new RegExp(name);  

    for (i = 0; i < document.forms[0].elements.length; i++)
    {
        var elem = document.forms[0].elements[i];
        if (elem.type == 'radio')
        {
           elem.checked = false;
        }
    }
    current.checked = true;
}

Later, set the script targeting the radio button control as given below: 稍后,设置针对单选按钮控件的脚本,如下所示:

Private Sub Repeater1_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles Repeater1.ItemDataBound
    Try
        If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
            If CType(e.Item.FindControl("hdf1"), Label).Text = False Then
                CType(e.Item.FindControl("rbtDinamic"), RadioButton).Visible = True
                CType(e.Item.FindControl("rbtDinamic"), RadioButton).GroupName = CType(e.Item.FindControl("groupvalue"), Label).Text = False
            End If
        End If

        ' put the proper client-side handler for RadioButton
        Dim radio As RadioButton = CType(e.Item.FindControl("rbtDinamic"), RadioButton)
        Dim script As String = "setExclusiveRadioButton('Repeater1.*[RadioButton_GroupName]', this)"

        radio.Attributes.Add("onclick", script)

    Catch ex As Exception          
    End Try
End Sub

NB: The first argument of setExclusiveRadioButton method should be set to this regex convention: [repeater control ID].*[RadioButton_GroupName] ( RadioButton_GroupName value may be retrieved using Eval ). 注意: setExclusiveRadioButton方法的第一个参数应设置为此正则表达式约定: [repeater control ID].*[RadioButton_GroupName] (可以使用Eval检索RadioButton_GroupName值)。 Alternatively you can use basic HTML input type="radio" or use RadioButtonList instead. 或者,您可以使用基本HTML input type="radio"或使用RadioButtonList

Reference: 参考:

Using RadioButton Controls in a Repeater 在Repeater中使用RadioButton控件

Similar issues: 类似问题:

radiobutton inside repeater 中继器内的radiobutton

only one radiobutton selection in repeater 在中继器中只选择一个单选按钮

ASP.NET - Radio Buttons In Repeaters ASP.NET - 中继器中的单选按钮

As other user provided the root cause of the problem , so i wouldn't be explaining same but i would provide you with the Jquery based solution: 由于其他用户提供了问题的根本原因,所以我不会解释相同,但我会为您提供基于Jquery的解决方案:

jQuery("[name$='$optValue']").attr("name",jQuery("[name$='$optValue']").attr("name"));

jQuery("[name$='$optValue]").click(function (){ 
                //set name for all to name of clicked 
                jQuery("[name$='$optValue]").attr("name", this.attr("name")); 
            });

with attr("name",jQuery("[name$='optValue']") will try to select all of the inputs on the page which ending with optValue ie optValue items in the repeater. after that it changes the name attribute to first value found for all the optValue elements. The attr("name") function (used here in 'get' format) always returns the first in the list. So all the option buttons get the same 'name' attribute in the Html, which allows the select to work correctly. with attr("name",jQuery("[name$='optValue']")将尝试选择页面上以optValue结尾的所有输入,即转发器中的optValue项目。之后,它将name属性更改为找到所有optValue元素的第一个值optValue attr("name")函数(此处以'get'格式使用)总是返回列表中的第一个。所以所有选项按钮在Html中都获得相同的'name'属性,这允许选择正常工作。

A great Work-around from this Source 这个来源的一个很好的解决方案

On the client side, set the name of the radio to whatever group you like, BUT write down the generated name in a data- attribute. 在客户端,将无线电的name设置为您喜欢的任何组,但是在data-属性中记下生成的名称。

Then, just before form submission, copy the data- attribute back to the name attribute, so the ASP.NET could recognize the control on the server. 然后,在表单提交之前,将data-属性复制回name属性,以便ASP.NET可以识别服务器上的控件。

This script will do it: 这个脚本会这样做:

<script type="text/javascript">
    $(document).ready(function (e) {            
        $("input[type='radio']").each(function (idx, elm) {
            var generatedName = $(elm).attr("name");
            $(elm).data("name", generatedName);
            $(elm).attr("name", "whatever-group-name");
        });

    });

    function onSubmit() {
        $("input[type='radio']").each(function (idx, elm) {
            var generatedName = $(elm).data("name");
            $(elm).attr("name", generatedName);
        });
    }
</script>

To detect the form submission, you do call RegisterOnSubmitStatement . 要检测表单提交,请调用RegisterOnSubmitStatement Eg in your Page_Load : 例如在你的Page_Load

if (!IsPostBack)
{
    Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "prepareSubmit", "onSubmit();");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM