HtmlInputCheckBox和Label for =

时间:2015-02-23 13:17:17

标签: c# asp.net webforms

假设我要在C#WebForms应用程序中使用后面的代码生成以下HTML。如何为复选框创建标签?

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

在此方法中添加可能的标签,或者使用文字是实现此目的的唯一方法吗?

2 个答案:

答案 0 :(得分:1)

好的,您可以向容器添加标签,并通过控件属性集合设置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;
}

答案 1 :(得分:0)

您可以使用标签控件

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