2

I would like to set the value of my label (or div) as an element and not text.

Example, this code creates a list of checkboxes as followed in this post How to use Checkbox inside Select Option :

<asp:Label runat="server" id="checkboxesList">
  <label for="one">
     <input type="checkbox" id="one" />First checkbox</label>
  <label for="two">
    <input type="checkbox" id="two" />Second checkbox</label>
  <label for="three">
    <input type="checkbox" id="three" />Third checkbox</label>
</asp:Label>

I need to create my List in CodeBehind and not directly in ASPX I tried :

checkboxesList.Text = "<label for=\"one\"> < input type = \"checkbox\" id = \"one\" /> First checkbox </ label > <label for= \"two\" > < input type = \"checkbox\" id = \"two\" /> Second checkbox </ label >";

Doing so it only prints as a string and do not create the differents labels. How to implement it from the code behind having just :

<asp:Label runat="server" id="checkboxesList">
</asp:Label>
Benoît
  • 143
  • 1
  • 2
  • 15

2 Answers2

0

It's not necessary to use server-side controls to generate all HTML elements. It is possible to use HTML directly for container elements. Use server-side controls only for elements that should be accessible from server code.

<div id="checkboxes">
    <label>
        <asp:CheckBox ID="one" runat="server" Text="First checkbox" />
    </label>
    <label>
        <asp:CheckBox ID="two" runat="server" Text="Second checkbox" />
    </label>
    <label>
        <asp:CheckBox ID="three" runat="server" Text="Third checkbox" />
    </label>
</div>

The snippet allows you to get/set values and text of checkboxes on server-side. Also you will be able to add server-side click event handler for each of the checkbox.

Note, the for attribute is used to bound the <label> with <input> that is not placed inside the <label>. Moreover the attribute is not supported by IE. So, in your case it is possible to place checkboxes into labels instead of using of for attribute.

Also you need to know the HTML id attribute in general case is not equal to ASP ID value. Therefore, if you want to link controls using for attribute, then set id attribute value through ClientID property.

Alexander
  • 4,420
  • 7
  • 27
  • 42
-1

Thank you all for the answers.

I've finally decided to use a CheckBoxList :

<asp:Label runat="server" id="LabelList">
    <asp:CheckBoxList runat="server" ClientIDMode="Predictable" DataValueField="Value" DataTextField="Name" ID="specificInfoListControl" Width="150">
    </asp:CheckBoxList>
</asp:Label>

And I retrieve the values with :

foreach (ListItem item in specificInfoListControl.Items)
{
  if (item.Selected)
  {
  }
}
Benoît
  • 143
  • 1
  • 2
  • 15
  • The markup that is generated by the snippet is not [valid HTML](https://validator.w3.org/docs/help.html#validation_basics). The [` – Alexander Oct 15 '18 at 15:45