我将 RadioButtonList 控件子类化,以便创建一个控件适配器,它可以完全按照我想要的方式输出 HTML(这是我第一次编写适配器)。
我面临的问题是在访问“SelectedValue”属性时,我总是得到一个空字符串。如果我切换到超类,我会得到正确的值,所以我真的很困惑......我在这里错过了什么?
我的子类再简单不过了:
namespace Internet.Webapp.Controls
{
public class RadioButtonList : System.Web.UI.WebControls.RadioButtonList
{
}
}
我的适配器也很简单:
public class RadioButtonListAdapter : System.Web.UI.Adapters.ControlAdapter
{
// Return a strongly-typed reference
public new Internet.Webapp.Controls.RadioButtonList Control
{
get
{
return (Internet.Webapp.Controls.RadioButtonList) base.Control;
}
}
protected override void Render(HtmlTextWriter writer)
{
RadioButtonList radioButtonList = Control;
writer.WriteBeginTag("div");
writer.WriteAttribute("id", radioButtonList.ClientID);
writer.Write(HtmlTextWriter.TagRightChar);
var counter = 0;
foreach (ListItem item in radioButtonList.Items)
{
writer.WriteFullBeginTag("div");
var itemId = radioButtonList.ClientID + "_" + counter++;
writer.WriteBeginTag("label");
writer.WriteAttribute("for", itemId);
writer.WriteAttribute("value", item.Text);
writer.WriteAttribute("class", "long");
writer.Write(HtmlTextWriter.TagRightChar);
writer.WriteBeginTag("input");
writer.WriteAttribute("type", "radio");
writer.WriteAttribute("id", itemId);
writer.WriteAttribute("name", radioButtonList.UniqueID);
writer.Write(HtmlTextWriter.TagRightChar);
writer.WriteEndTag("input");
writer.Write(item.Text);
writer.WriteEndTag("label");
writer.WriteEndTag("div");
}
writer.WriteEndTag("div");
}
}
填充单选按钮列表的代码如下:
var radioButtonList = new Controls.RadioButtonList();
optionsList.ForEach(option => radioButtonList.Items.Add(option));
和生成的html:
<div id="ctl00_MainSection_CordaanForm_ctl14">
<div>
<label for="ctl00_MainSection_CordaanForm_ctl14_0" value="male" class="long">
<input type="radio" id="ctl00_MainSection_CordaanForm_ctl14_0" name="ctl00$MainSection$CordaanForm$ctl14"></input>
male
</label>
</div>
<div>
<label for="ctl00_MainSection_CordaanForm_ctl14_1" value="female" class="long">
<input type="radio" id="ctl00_MainSection_CordaanForm_ctl14_1" name="ctl00$MainSection$CordaanForm$ctl14"></input>
female
</label>
</div>
</div>