7

I am converting an HTML code that uses Bootstrap 3 into ASP.NET Web Form. The Bootstrap 3 class "form-group" has a tag with "For" attribute. For example:

<div class="form-group">
    <label for="txtField" class="control-label">Caption:</lable>
    <input type="text" id="txtField" name="txtField" class="form-control" />
</div>

I am converting the above code into using controls as:

<div class="form-group">
    <asp:label class="control-label">Caption:></asp:lable>
    <asp:TextBox id="txtField" class="form-control" /asp:TextBox>
</div>

But <asp:TextBox> does not have an attribute "name" and <asp:Label> does not have attribute "for". What should I use instead? Or it does not matter at all if I skip these attributes?

Babak Naffas
  • 12,395
  • 3
  • 34
  • 49
Hidalgo
  • 941
  • 2
  • 14
  • 38

3 Answers3

11

Use AssociatedControlID:

<asp:Label runat="server" CssClass="control-label" AssociatedControlID="txtField">Caption</asp:Label>
<asp:TextBox runat="server" ID=txtField" CssClass="form-control" />

From the MSDN documentation page:

When the AssociatedControlID property is set, the Label control renders as an HTML label element, with the for attribute set to the ID property of the associated control. You can set other attributes of the label element using the Label properties. For example, you can use the Text and AccessKey properties to provide the caption and hot key for an associated control.

As an aside, it seems that many people seem to think that omitting these attributes will have no effect where the reality is that it can have a profound effect on some users; specifically users with screen readers.

Screen readers use the for attribute on labels to tell the user what they are expected to enter when they encounter a form control. So not only should you endeavour to include these attributes in your web applications, you should also aim to make the content of the label as descriptive as possible.

Sean Airey
  • 6,352
  • 1
  • 20
  • 38
1

For label use

<asp:Label class="control-label" runat="server" AssociatedControlId="txtField">Caption:></asp:Label>

Name of textbox is au generated. If you want to have predicted names use ClientIDMode property with e.g value static.

Marcin
  • 3,232
  • 4
  • 31
  • 48
0

There is an effect in skipping those attributes, in general.

What is the effect of the 'for' attribute? See here. It changes the behaviour of the label in a minor way (so, not critical).

What is the effect of the 'name' attribute? In general, this IS critical, as it is the primary way of identifying fields between client and server. However, if ASP is managing that for you (and it's working), you may not need it.

Another approach is to anticipate what the 'name' attribute WILL be, and put that in the label's 'for' attribute.

Community
  • 1
  • 1
mcsilvio
  • 1,098
  • 1
  • 11
  • 20