Blog from Saravanan Arumugam

Let us talk about Technologies

Friendly Names in MVC Html Helper created labels


Html helpers that come with MVC are smart enough to find the kind of field we try to work on and produce HTML accordingly. For instance, if I use the EditorFor() method

@Html.EditorFor()

for an integer or string, it’ll generate text box as the editor in the resulting HTML. If EditorFor() is applied on a Boolean, it’ll display a checkbox as the editor.

We have many helper methods that we can find very useful while writing MVC views. Most frequently used ones include,

@Html.EditorFor()
@Html.DisplayFor()
@Html.LabelFor()

Friendly Names

When we use LabelFor(), it would usually display the Property name (The variable name). For example, when I write the following, it simply displays the text “HasBranchesOverseas” on the Web page.

@Html.LabelFor(modelItem => item.HasBranchesOverseas)

On a web page we want the friendly names to be displayed not the variables names.

To provide a friendly name to the property, use System.ComponentModel. DisplayNameAttribute.

[DisplayName(“Has Branches Overseas”)]
public
 bool HasBranchesOverseas { get; set; }

 Now if you use @Html.LabelFor(), you’d see “Has Branches Overseas” on the web page, instead of the plain variable name.

Advertisements

2 responses to “Friendly Names in MVC Html Helper created labels

  1. Pingback: Learn data binding with .Net objects « Blog from Saravanan Arumugam

  2. Pingback: User friendly name for Enumeration fields « Blog from Saravanan Arumugam

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: