I have subclassed the RadioButtonList control in order to create a Control Adapter that outputs the HTML exactly the way I want (it is the first time I write an adapter).
The problem that I am facing is when accessing the "SelectedValue" property, I always get an empty string. If I switch to the superclass I get the proper value, so I am really puzzled... What am I missing here?
My subclass couldn't be simpler:
namespace Internet.Webapp.Controls
{
public class RadioButtonList : System.Web.UI.WebControls.RadioButtonList
{
}
}
My adapter is also very simple:
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");
}
}
The code to populate the radio button list is the following:
var radioButtonList = new Controls.RadioButtonList();
optionsList.ForEach(option => radioButtonList.Items.Add(option));
And the generated 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>