To contact Ben MacGowan, please fill in the below form. Note that required fields are marked with a blue left border.

Close

Please fill in all required fields before submitting

Achieving user friendly Labels with .NET

Making your forms as user friendly as possible is something we all strive for and one common technique is to make our form labels clickable – focusing on the relevant input field upon click.

This can easily be achieved by using the for attribute:

<label for="inputSample">Label</label>
<input type="text" id="inputSample" />

Simple enough when coding with HTML, but with .NET Controls, it requires a bit more knowledge in achieving the same effect. From my own experience, you will come across the following problems:

  • When using the for attribute, you need to know the ID of the relevant input. With .NET, the ID renders differently depending on the namspace of the page, whether is in a master page or user control. For example, if I were to give an input field the ID “inputSample”, this would render something a long the lines of “ct100_inputSample”, or within a user control “ct100_usercontrolName_inputSample”. So as you can see, ID’s in .NET aren’t as straight forward.
  • Straight out of the box, the asp:label tag renders as a span on the page rather than the label we were hoping for. Which doesn’t really help when it comes to styling the form with CSS.

Therefore, in order to match the ID of the input and to render the tag as a label, we would use the AssociatedControlID attribute. By giving this attribute the same value as the input ID, the label’s for value and input ID value would match up. The asp:label tag also now renders as a label.

<asp:Label id="lblSample" runat="server" 
    text="Label Text" AssociatedControlID="txtSample" />
<asp:Textbox id="txtSample" runat="server" />

For added effect, apply a CSS style of cursor: pointer to the label so the user realises these fields are clickable.

1 Comment

 

*shudders* … ASP….

But woot for writing about this stuff though, when I was working with it a year ago there really weren’t many good resources/tutorials (simple ones). :D

Melissa / http://melly.me / 28 Sep 2009

Leave Comment

Required fields are marked with a blue left border.

Gravatar