C#.Net - RadioButton控制适配器和回发

时间:2009-10-20 04:37:46

标签: c# asp.net controls postback control-adapter

我有一个单选按钮控件适配器,它尝试使用CSS类作为输入标记的一部分呈现单选按钮控件,而不是作为周围的跨度。

public class RadioButtonAdapter : WebControlAdapter
{
    protected override void Render(HtmlTextWriter writer)
    {
        RadioButton targetControl = this.Control as RadioButton;

        if (targetControl == null)
        {
            base.Render(writer);

            return;
        }                    

        writer.AddAttribute(HtmlTextWriterAttribute.Id, targetControl.ClientID);
        writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio");        
        writer.AddAttribute(HtmlTextWriterAttribute.Name, targetControl.GroupName); //BUG - should be UniqueGroupName        
        writer.AddAttribute(HtmlTextWriterAttribute.Value, targetControl.ID);
        if (targetControl.CssClass.Length > 0)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Class, targetControl.CssClass);
        }        

        if (targetControl.Page != null)
        {
            targetControl.Page.ClientScript.RegisterForEventValidation(targetControl.GroupName, targetControl.ID);
        }
        if (targetControl.Checked)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked");
        }            
        writer.RenderBeginTag(HtmlTextWriterTag.Input);
        writer.RenderEndTag();

    }
}

目前,这呈现的非常接近我想要的,唯一的区别是组名属性(标准单选按钮使用内部值UniqueGroupName,而我只使用GroupName。我似乎无法找到方法获取UniqueGroupName,下面的行应该反击:

targetControl.Page.ClientScript.RegisterForEventValidation(targetControl.GroupName, targetControl.ID);

带有标准单选按钮的旧HTML -

<span class="radio">
<input id="ctl00_ctl00_mainContent_RadioButton1" type="radio" value="RadioButton1" name="ctl00$ctl00$mainContent$mygroup"/>
</span>

新渲染 -

<input id="ctl00_ctl00_mainContent_RadioButton1" class="radio" type="radio" value="RadioButton1" name="mygroup"/>

问题是回发不起作用 - RadioButton1.Checked值始终为false。关于如何在回发中获得单选按钮值的任何想法?

1 个答案:

答案 0 :(得分:3)

回发无效的原因是因为在返回时,字段名称与ASP.NET的预期不符。因此,它不是一个理想的解决方案,但您可以使用反射来获取UniqueGroupName:

using System.Reflection;

//snip...

RadioButton rdb = this.Control as RadioButton;
string uniqueGroupName = rdb.GetType().GetProperty("UniqueGroupName",
    BindingFlags.Instance | BindingFlags.NonPublic).GetValue(rdb, null) as string;

或为了清晰起见分成不同的行:

Type radioButtonType = rdb.GetType(); //or typeof(RadioButton)

//get the internal property
PropertyInfo uniqueGroupProperty = radioButtonType.GetProperty("UniqueGroupName",
    BindingFlags.Instance | BindingFlags.NonPublic);

//get the value of the property on the current RadioButton object
object propertyValue = uniqueGroupProperty.GetValue(rdb, null);

//cast as string
string uniqueGroupName = propertyValue as string;