ASP.Net CheckBoxes should be able to have values
The ASP.Net CheckBox and CheckBoxList control don’t allow for the use of the full W3C HTML standard. For some reason Microsoft decided to implement a reduced functionality version that creates more work for the programmer. Come on Microsoft why can’t you follow even the simplest of standards? In this case it would make coding the .Net framework easier for you not to mention us!
The W3C HTML 4.01 specification specifically states for the value attribute to:
– Specify for radio buttons and checkboxes –
W3C HTML 4.01 Specification – INPUT Element
To me this quote reads as a strong recommendation to specify the value attribute rather than leave it up to the browsers default (generally "On"). Microsoft decided to not even allow the value attribute to be set. They went so far as to have a validation message built into Visual Studio that says:
Attribute ‘Value’ is not a valid attribute of element ‘CheckBox’
If you ignore the warning and run the page, the value attribute is missing. I have even tried circumventing the ASP.Net HTML-izer by adding value to the attributes collection with no success. Microsoft intentionally strips it, so I can only assume they have some reasoning behind this behavior and I imagine they will say something about security in defense.
There is one way to circumvent the behavior but it requires not using ASP.Net controls. Simply insert traditional input type=”checkbox” elements into your page and collect their values using Request.Form.
Sub Page_Load () Dim value As String value = Request.Form("chkItem") End Sub … <input type="checkbox" id="chkItem" name="chkItem" /> <label for="chkItem">CheckBox Item Text</label>
I made a big deal out of this issue simply because to me it doesn’t make any sense. You can get around the issue and still use ASP.Net controls but it requires extra coding.
Sub Page_Load () Dim value As String If chkItem.Checked Then value = "Some Value" Else value = "Some Other Value" End If End Sub … <asp:CheckBox ID="chkItem" Text="CheckBox Item Text" runat="server" />
When using the CheckBoxList control you will notice ASP.Net uses tables to layout the list. To keep it from doing this you simply need to add a few attributes. It should then use much more standards compliant code. I also show how to access which boxes are checked after postback in a CheckBoxList.
Sub Page_Load () ' Find out which boxes were checked Dim value As String = "" For Each item As ListItem In cblTest.Items If item.Selected Then value &= item.Value End If Next End Sub … <asp:CheckBoxList ID="cblList" RepeatLayout="Flow" RepeatDirection="Horizontal" runat="server"> <asp:ListItem Text="Item 1" Value="1" /> <asp:ListItem Text="Item 2" Value="2" /> <asp:ListItem Text="Item 3" Value="3" /> </asp:CheckBoxList>
As always let me know if you have any questions.