2012-12-05 36 views
8

我以編程方式將複選框添加到ASP.NET WebForm。我想遍歷Request.Form.Keys並獲取複選框的值。 ASP.NET複選框沒有值屬性。將值屬性添加到ASP.NET複選框

如何設置value屬性,以便在遍歷Request.Form.Keys時獲得比默認「on」更有意義的值。

代碼添加複選框的頁面:

List<string> userApps = GetUserApplications(Context); 

Panel pnl = new Panel(); 

int index = 0; 
foreach (BTApplication application in Userapps) 
{ 
    Panel newPanel = new Panel(); 
    CheckBox newCheckBox = new CheckBox(); 

    newPanel.CssClass = "filterCheckbox"; 
    newCheckBox.ID = "appSetting" + index.ToString(); 
    newCheckBox.Text = application.Name; 

    if (userApps.Contains(application.Name)) 
    { 
     newCheckBox.Checked = true; 
    } 

    newPanel.Controls.Add(newCheckBox); 
    pnl.Controls.Add(newPanel); 

    index++; 
} 

Panel appPanel = FindControlRecursive(this.FormViewAddRecordPanel, "applicationSettingsPanel") as Panel; 

appPanel.Controls.Add(pnl); 

代碼從的Request.Form檢索複選框值:

StringBuilder settingsValue = new StringBuilder(); 

foreach (string key in Request.Form.Keys) 
{ 
    if (key.Contains("appSetting")) 
    { 
     settingsValue.Append(","); 
     settingsValue.Append(Request.Form[key]); 
    } 
} 

回答

16

InputAttributes.Add()!

以下不起作用,因爲「複選框控件不呈現歸因值(實際上在呈現事件相去除屬性[)]。」:

newCheckBox.Attributes.Add("Value", application.Name); 

解決方案:

newCheckBox.InputAttributes.Add("Value", application.Name); 

感謝Dave Parslow的博文:Assigning a value to an ASP.Net CheckBox