【发布时间】:2020-06-22 03:00:20
【问题描述】:
我的页面中有一个中继器控件。在选中一个单选按钮时,我需要在所有行(项目模板)中有一个单选按钮,其余单选按钮必须取消选中。
如何做到这一点?
提前致谢, 托尔
【问题讨论】:
标签: asp.net
我的页面中有一个中继器控件。在选中一个单选按钮时,我需要在所有行(项目模板)中有一个单选按钮,其余单选按钮必须取消选中。
如何做到这一点?
提前致谢, 托尔
【问题讨论】:
标签: asp.net
不幸的是,GroupName 属性在中继器中使用时无法按预期工作,这是一个已知错误 (http://support.microsoft.com/kb/316495)。问题在于Repeater 实现了INamingContainer 接口,该接口要求所有嵌套控件在呈现为HTML 时具有唯一名称。这会导致单选按钮中断,因为为了使它们正常工作,它们必须具有相同的名称。
我遇到了两种解决方法:
1 - 第一个是客户端 javascript 解决方案。它由Microsoft support 提供。或者更容易阅读的版本here。 说明如下。在 HEAD 中包含以下 javascript:
function SetUniqueRadioButton(nameregex, current)
{
re = new RegExp(nameregex);
for(i = 0; i < document.forms[0].elements.length; i++)
{
elm = document.forms[0].elements[i]
if (elm.type == 'radio')
{
if (re.test(elm.name))
{
elm.checked = false;
}
}
}
current.checked = true;
}
现在该函数需要链接到中继器的 OnDataItemBound 事件中的单选按钮。将“RadioButton”替换为您的 RadioButton 控件的名称,将“RadioGroup”替换为您选择的 GroupName:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
RadioButton rb = (RadioButton) e.Item.FindControl("RadioButton");
string script = "SetUniqueRadioButton('Repeater1.*RadioGroup',this)";
rb.Attributes.Add("onclick", script);
}
2 - 第二种解决方案是使用从 RadioButton 继承的自定义用户控件的服务器端解决方案。教程和源码可以在这里下载:http://www.codeproject.com/KB/webforms/How_group_RButtons.aspx
【讨论】:
只需将OnCheckedChanged 事件添加到单选按钮,循环中继器中的所有单选按钮以取消选中它们。如果您不想回发,可以使用UpatePanel。
.aspx
<asp:Repeater ID="Repeater1" runat="server" >
<ItemTemplate>
<asp:RadioButton ID="RadioButton1" runat="server" OnCheckedChanged="RadioButton1_OnCheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:Repeater>
.cs
protected void RadioButton1_OnCheckedChanged(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
RadioButton rbtn = (RadioButton)item.FindControl("RadioButton1");
rbtn.Checked = false;
}
((RadioButton)sender).Checked = true;
}
【讨论】:
我知道这是旧的,但按钮不起作用的原因是名称属性被覆盖。如果使用 jQuery,您可以将单选按钮分配给一个类,然后设置 name 属性以覆盖新名称。
$('.MyRadioClass').attr("name","MyFixedName");
【讨论】:
另一个更简单的替代方法是使用 RadioButtonList:
<asp:RadioButtonList ... />
【讨论】: