1

我有一个单选按钮控件适配器,它尝试将带有 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 值始终为假。关于如何在回发中获取单选按钮的值的任何想法?

4

1 回答 1

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;
于 2009-10-20T04:53:09.693 回答