HtmlInputCheckBox 和标签=

HtmlInputCheckBox and Label for=

假设我有以下 HTML 我想从 C# WebForms 应用程序中的代码生成。如何为复选框创建标签?

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>

代码隐藏

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

在此方法中是否可能添加标签或使用文字是完成此操作的唯一方法?

好的,你可以给容器添加一个标签,并通过控件属性集合设置for=,如下所示。

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

可以利用标签控件

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