我想你说的是 RadioButtonList。它的问题在于它使用 RadioButton 控件,并且它具有 3 个属性属性 - Attributes、InputAttributes 和 LabelAttributes。它们中的每一个都用于特定的 html 元素。
RadioButtonList 的问题在于它只使用 Attributes 属性,而不使用 InputAttributes。这是 RadioButtonList.RenderItem 方法的代码:
protected virtual void RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
{
if (repeatIndex == 0)
{
this._cachedIsEnabled = this.IsEnabled;
this._cachedRegisterEnabled = this.Page != null && !this.SaveSelectedIndicesViewState;
}
RadioButton controlToRepeat = this.ControlToRepeat;
int index1 = repeatIndex + this._offset;
ListItem listItem = this.Items[index1];
controlToRepeat.Attributes.Clear();
if (listItem.HasAttributes)
{
foreach (string index2 in (IEnumerable) listItem.Attributes.Keys)
controlToRepeat.Attributes[index2] = listItem.Attributes[index2];
}
if (!string.IsNullOrEmpty(controlToRepeat.CssClass))
controlToRepeat.CssClass = "";
ListControl.SetControlToRepeatID((Control) this, (Control) controlToRepeat, index1);
controlToRepeat.Text = listItem.Text;
controlToRepeat.Attributes["value"] = listItem.Value;
controlToRepeat.Checked = listItem.Selected;
controlToRepeat.Enabled = this._cachedIsEnabled && listItem.Enabled;
controlToRepeat.TextAlign = this.TextAlign;
controlToRepeat.RenderControl(writer);
if (!controlToRepeat.Enabled || !this._cachedRegisterEnabled || this.Page == null)
return;
this.Page.RegisterEnabledControl((Control) controlToRepeat);
}
controlToRepeat 就是那个 RadioButton,它只指定了 Attributes 属性而忽略了 InputAttributes。
我可以建议修复它的方法 - 您可以创建继承 RadioButtonList 的新类,并使用它而不是默认值。这是该类的代码:
public class MyRadioButtonList : RadioButtonList
{
private bool isFirstItem = true;
protected override void RenderItem(ListItemType itemType, int repeatIndex, RepeatInfo repeatInfo, HtmlTextWriter writer)
{
if (isFirstItem)
{
// this.ControlToRepeat will be created during this first call, and then it will be placed into Controls[0], so we can get it from here and update for each item.
var writerStub = new HtmlTextWriter(new StringWriter());
base.RenderItem(itemType, repeatIndex, repeatInfo, writerStub);
isFirstItem = false;
}
var radioButton = this.Controls[0] as RadioButton;
radioButton.InputAttributes.Clear();
var item = Items[repeatIndex];
foreach (string attribute in item.Attributes.Keys)
{
radioButton.InputAttributes.Add(attribute, item.Attributes[attribute]);
}
// if you want to clear attributes for top element, in that case it's a span, then you need to call
item.Attributes.Clear();
base.RenderItem(itemType, repeatIndex, repeatInfo, writer);
}
}
稍微说明一下——它有 isFirstItem 属性,因为它使用的 RadioButton 控件是在第一次访问时在运行时创建的,所以我们需要先调用 RenderItem 才能更新 InputAttrubutes 属性。所以我们调用它一次并发送一些存根 HtmlTextWriter,所以它不会显示两次。之后,我们将这个控件作为 Controls[0] 获取,并为每个 ListItem 更新 InputAttributes 值。
PS。抱歉,我没有使用 VB.Net,所以控件是用 C# 编写的