9

我以编程方式将复选框添加到 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]);
    }
}
4

1 回答 1

17

输入属性。添加()!

以下内容不起作用,因为“CheckBox 控件不呈现属性值(它实际上在呈现事件阶段 [)] 期间删除了属性。”:

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

解决方案:

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

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

于 2012-12-05T21:52:40.647 回答