简体   繁体   中英

Add value attribute to ASP.NET Checkbox

I'm programmatically adding checkboxes to a ASP.NET WebForm. I want to iterate through the Request.Form.Keys and get the value of the checkboxes. ASP.NET Checkboxes don't have a value attribute.

How do I set the value attribute so that when I iterate through the Request.Form.Keys I get a more meaningful value than the default "on".

Code for adding the checkboxes to the page:

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);

Code for retrieving checkbox values from Request.Form:

StringBuilder settingsValue = new StringBuilder();

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

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

The following doesn't work because:

the CheckBox control does not render the value attributed (it actually removes the attribute during the render event phase).

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

The solution:

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

Thanks to Dave Parslow's blog post: Assigning a value to an ASP.Net CheckBox

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM