C#中BE属性的标签

时间:2013-01-10 09:20:29

标签: c# asp.net-mvc

在我的BE类中,我有一些与表字段匹配的属性。我想为每个属性公开描述性名称。例如,将其显示为网格中的列标题。

例如,有一个名为FirstName的属性。我想将其描述性名称公开为First Name

为此,我创建了一个对数组作为此BE类的属性。 ,myarray("FirstName","First Name") 有没有更好的方法呢?

3 个答案:

答案 0 :(得分:3)

您可以在模型中执行此操作:

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

然后在您的视图中,您可以像这样引用标签名称:

@Html.DisplayFor(m=>m.FirstName)

答案 1 :(得分:3)

您可以在BE属性上使用[DisplayName("First name")]属性。

然后在视图中使用: @Html.LabelFor(m=>m.FirstName)

关于SO的类似问题:How to change the display name for LabelFor in razor in mvc3?

修改

您还可以在所有BE属性上使用[Display(Name="First name")]属性。 然后创建一个用于显示BE的模板(更多信息如何在此处创建模板:How do I create a MVC Razor template for DisplayFor())。

然后在视图中您只需使用:

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

答案 2 :(得分:0)

我觉得这很有用,这就是我解决它的方法。我发布这个,因为它可能对其他人有用。

BE中的

定义了这个。

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

您可以阅读以下每个属性的详细信息;

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"
    */
}
  • 其中objectBE是BE类的对象实例。