从RadioButtonList子类中获取SelectedValue

时间:2009-12-15 10:59:45

标签: asp.net adapter radiobuttonlist

我已经将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>

1 个答案:

答案 0 :(得分:1)

ASP.NET通过ID识别控件。您在重写Render方法时更改了该ID,因此框架无法再识别它。