2011-05-06 62 views
1

我創建了一個基於類似code example for a custom CheckBoxList呈現爲無序列表的自定義RadioButtonList。自定義RadioButtonList丟失回傳值

但由於某種原因,我的選定項目在執行回發時未保存。 我overrided的唯一方法是渲染法:

[ToolboxData("<{0}:ULRadioButtonList runat=server></{0}:ULRadioButtonList>")] 
public class ULRadioButtonList : RadioButtonList { 
    protected override void Render(HtmlTextWriter writer) { 
     Controls.Clear(); 

     string input = "<input id={0}{1}{0} name={0}{2}{0} type={0}radio{0} value={0}{3}{0}{4} />"; 
     string label = "<label for={0}{1}{0}>{2}</label>"; 
     string list = "<ul>"; 

     if (!String.IsNullOrEmpty(CssClass)) { 
      list = "<ul class=\"" + CssClass + "\">"; 
     } 

     writer.WriteLine(list); 

     for (int index = 0; index < Items.Count; index++) { 
      writer.Indent++; 
      writer.Indent++; 

      writer.WriteLine("<li>"); 

      writer.Indent++; 

      StringBuilder sbInput = new StringBuilder(); 
      StringBuilder sbLabel = new StringBuilder(); 

      sbInput.AppendFormat(
       input, 
       "\"", 
       base.ClientID + "_" + index.ToString(), 
       base.UniqueID, 
       base.Items[index].Value, 
       (base.Items[index].Selected ? " checked=\"\"" : "") 
      ); 

      sbLabel.AppendFormat(
       label, 
       "\"", 
       base.ClientID + "_" + index.ToString(), 
       base.Items[index].Text 
      ); 

      writer.WriteLine(sbInput.ToString()); 
      writer.WriteLine(sbLabel.ToString()); 

      writer.Indent = 1; 

      writer.WriteLine("</li>"); 

      writer.WriteLine(); 

      writer.Indent = 1; 
      writer.Indent = 1; 
     } 

     writer.WriteLine("</ul>"); 
    } 
} 

我是不是忘了什麼東西?如果我使用常規的ASP.NET RadioButtonList,則在回發後保存我選擇的項目,所以沒有任何內容覆蓋我的值;它與自定義控件有關。

回答

0

對於這樣的方法來工作,你必須匹配name(和id)在與的RadioButtonList生成標記屬性。因此,在你的代碼明顯的問題是name屬性值 - 它應該與每個單選按鈕的索引被追加即

... 
sbInput.AppendFormat(
      input, 
      "\"", 
      base.ClientID + "_" + index.ToString(), 
      base.UniqueID + index.ToString(), // <<< note the change here 
      base.Items[index].Value, 
... 

,而不是同樣「_」的ID生成,你應該使用ClientIdSeparator屬性。

最後,我必須建議您採用這種控制創作方法,因爲它本質上很脆弱,即如果底層ASP.NET控件如何生成其標記,它可能會中斷。例如,在ASP.NET中,可以配置客戶端ID生成邏輯,因此您的ID生成邏輯可能無法正確匹配基本控件生成的原始標記。

+0

名稱屬性必須與我列表中的所有單選按鈕相同,否則我可以選擇多個單選按鈕,這不是單選按鈕的用途。 – thomasvdb 2011-05-06 09:23:03

+0

@thomasvb,是的 - 我在提示更改名稱屬性時出錯 - 我只是交叉檢查並且ASP.NET也生成了相同的名稱屬性。在這種情況下,我認爲這個問題可能與身份證生成有關。我會建議你評論你的渲染實現,並查看生成的單選按鈕的ID並將其與渲染實現生成的ID進行比較。 – VinayC 2011-05-09 04:08:05