我想你是在谈论RadioButtonList。问题在于它使用RadioButton控件,它有3个属性属性 - 属性,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是单选按钮,而且只规定了财产的属性,而忽略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财产,为使用它在第一次访问运行时创建单选按钮控制,所以我们需要调用RenderItem才可以更新InputAttrubutes属性。所以我们调用它一次并发送一些存根HtmlTextWriter,所以它不会显示两次。然后,我们只需将这个控件作为Controls [0],并且为每个ListItem我们更新InputAttributes值。
PS。对不起,我没有使用VB.Net所以控制是用C#编写的。
CheckboxList项是否遭受同样的问题,因此也需要覆盖? –
另外,如何防止它在两个位置呈现属性呢?现在我正在获取span标签和输入标签的属性。所以这是另一个问题。 –
是的,CheckBoxList有同样的问题。但是,对于使用RadioButton控件的RadioButtonList,CheckBoxList使用CheckBox控件。 RadioButton继承了CheckBox。 –