将值属性添加到ASP.NET复选框

时间:2012-12-05 21:52:41

标签: c# asp.net

我正在以编程方式向ASP.NET WebForm添加复选框。我想迭代Request.Form.Keys并获取复选框的值。 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]);
    }
}

1 个答案:

答案 0 :(得分:16)

InputAttributes.Add()!

以下方法不起作用,因为“CheckBox控件不会呈现属性值(它实际上在渲染事件阶段[]中删除了属性]。”:

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

解决方案:

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

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