【问题标题】:ASP.NET MVC - Show raw DisplayName of an item of the ModelASP.NET MVC - 显示模型项目的原始 DisplayName
【发布时间】:2018-12-05 12:07:31
【问题描述】:

例如我有课

public class Car
 {
     public string Name { get; set; }
     public string Brand { get; set; }
     public string Color { get; set; }
 }

我有一个模型作为列表的视图

@model IEnumerable<Car>

现在我想显示 listItem(模型)的属性的原始 displayName。

示例代码:

@model IEnumerable<Car>

//(..)

<thead>
    <tr>
        <th>"[@Html.DisplayName(Model.First().Name))]"</th>
        <th>Brand</th>
        <th>Color</th>
    </tr>
</thead>

我该怎么做?

更新

我在创建一个新的帮助类时找到了解决方案: click me

【问题讨论】:

标签: asp.net asp.net-mvc model-view-controller


【解决方案1】:

你可以得到

<th>DisplayName</th>

通过使用

@Html.DisplayNameFor(model => model.First().Name)

您使用的解决方案很旧,并且没有使用内置帮助器。

【讨论】:

    【解决方案2】:

    使用标签

    <th>@Html.LabelFor(p => p.First().Name)<th>
    

    别忘了 Car Class 的 display 属性

    [DisplayName("Car Name")]
    public string Name { get; set; }
    

    【讨论】:

    • with LabelFor 我会在“标签”中获得我想要的显示名称,但我想要原始值:&lt;th&gt;Name&lt;/th&gt; 而不是&lt;th&gt;&lt;label&gt;Name&lt;/label&gt;&lt;/th&gt;
    • 好的,你可以使用System.Reflection通过反射得到它; var name = ((DisplayAttribute)(typeof(Car).GetProperty("Name").GetCustomAttribute(typeof(DisplayAttribute)))).Name;
    猜你喜欢
    • 2011-07-26
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多