HtmlInputCheckBox and Label for=

2019-08-15 19:35发布

问题:

Say I have the below HTML that I want to generate from the code behind in a C# WebForms application. How do I create the label for the checkbox?

HTML

<div class="col-lg-8 col-lg-offset-1">
    <input id="combo" type="checkbox" value="false" />
    <label for="combo" class="margin">Text Here</label>
</div>

Code behind

private static HtmlGenericControl CreateHtmlInputCheckBoxControl(Filters filter)
{
    HtmlGenericControl column = CreateColumn(filter);
    column.Controls.Add(new HtmlInputCheckBox { Checked = false, Value = filter.Caption });
    return column;
}

private static HtmlGenericControl CreateColumn(Filters filter, string additionalClasses = "")
{
    HtmlGenericControl div = new HtmlGenericControl("div");
    div.Attributes["class"] = string.Format("col-lg-{0} col-lg-offset-{1} {2}", filter.ColumnSpan, filter.ColumnOffset, additionalClasses);
    return div;
}

Is adding a label for possible in this method or is using a literal the only way to accomplish this?

回答1:

OK, you can add a label to the container and set the for= via the controls Attributes collection as below.

private static HtmlGenericControl CreateHtmlInputCheckBoxControl(Filters filter)
{
    HtmlGenericControl column = CreateColumn(filter);
    column.Controls.Add(new HtmlInputCheckBox { ID = string.Format("{0}{1}", filter.ID, filter.ReportID), Checked = false });

    HtmlGenericControl l = new HtmlGenericControl("label"){InnerText=filter.Caption};       
    l.Attributes["for"]= string.Format("{0}{1}", filter.ID, filter.ReportID);
    column.Controls.Add(l);

    return column;
}


回答2:

You can make use of the label control

Label l = new Label
{
  Text = filter.Caption,
  AssociatedControlID = string.Format("{0}{1}", filter.ID, filter.ReportID)
};
column.Controls.Add(l);

https://msdn.microsoft.com/en-us/library/system.windows.forms.label(v=vs.110).aspx