0

In my BE class I have certain properties to match with table fields. I want to expose descriptive name for each of these properties. for example to show it as column header in grid.

For example, there is a property called FirstName. I want to expose it's descriptive name as First Name

For this, I have created an array of pairs as a property of this BE class. i.e, myarray("FirstName","First Name") Is there a better way of doing this?

Firnas
  • 1,665
  • 4
  • 21
  • 31

3 Answers3

3

You can do this in your model:

[Display(Name = "First Name")]
public string FirstName { get; set; }

And then in your View you can reference the label name like this:

@Html.DisplayFor(m=>m.FirstName)
robasta
  • 4,621
  • 5
  • 35
  • 53
  • 1
    `DisplayFor` will display `FirstName` value (using default or predefined template), not the *name* of the property. You probably mean `@Html.DisplayNameFor(m=>m.FirstName)`. – mipe34 Jan 10 '13 at 09:49
3

You can use [DisplayName("First name")] attribute on your BE property.

And then in view use: @Html.LabelFor(m=>m.FirstName)

Similar question here on SO: How to change the display name for LabelFor in razor in mvc3?

EDIT

You can also use the [Display(Name="First name")] attribute on all of your BE properties. Then create a template for displaying your BE (more info how to create template here: How do I create a MVC Razor template for DisplayFor()).

And then in the view you would simply use:

@Html.DisplayFor(m=>m, "MyModelTemplateName")

Community
  • 1
  • 1
mipe34
  • 5,596
  • 3
  • 26
  • 38
0

I found this useful and this is how I solved it. I'm posting this since it might be useful for others.

in BE define this.

[DisplayName("First Name"), Description("First Name of the Member")]
public string FirstName
{
    get { return _firstName; }
    set { _firstName = value; }
}

You can read these details of each property as below;

PropertyDescriptorCollection propertiesCol = TypeDescriptor.GetProperties(objectBE);

PropertyDescriptor property;

for (int i = 0; i < propertiesCol.Count; i++)
{
    property = TypeDescriptor.GetProperties(objectBE)[i];

    /*
    // Access the Property Name, Display Name and Description as follows
    property.Name          // Returns "FirstName"
    property.DisplayName   // Returns "First Name"
    property.Description   // Returns "First Name of the Member"
    */
}
  • where objectBE is the object instance of BE class.
Firnas
  • 1,665
  • 4
  • 21
  • 31