为ASP.NET复选框添加value属性

9
我正在以编程方式向ASP.NET WebForm添加复选框。我想遍历Request.Form.Keys并获取复选框的值。ASP.NET复选框没有value属性。
如何设置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个回答

17

CheckBox.InputAttributes.Add()! - learn.microsoft.com

以下代码不起作用,因为:

CheckBox控件在呈现事件阶段会移除属性的值,导致该属性无法呈现。

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

解决方案:

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

感谢Dave Parslow的博客文章:为ASP.Net CheckBox分配一个值


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接