2009-10-20 26 views
1

我有一個單選按鈕控件適配器,它嘗試使用CSS類作爲輸入標記的一部分呈現單選按鈕控件,而不是作爲周圍的跨度。C#.Net - RadioButton控制適配器和回發

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,而我只用組名。我似乎無法到找到一個辦法讓UniqueGroupName,和線下無論如何都應該解決這個:

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

老buttons- HTML標準的無線電

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

新rendering-

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

問題是回發不起作用 - RadioButton1.Checked值始終爲false。任何想法如何獲得單選按鈕的價值在回發?

回答

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; 
+0

謝謝,非常完美。 – Spongeboy 2009-10-20 05:00:39