我知道已经有关于此的其他线程。我一直在读它们。这是我得到的:
namespace Books.Entities
{
public enum Genre
{
[Display(Name = "Non Fiction")]
NonFiction,
Romance,
Action,
[Display(Name = "Science Fiction")]
ScienceFiction
}
}
型号:
namespace Books.Entities
{
public class Book
{
public int ID { get; set; }
[Required]
[StringLength(255)]
public string Title { get; set; }
public Genre Category { get; set; }
}
}
然后,在 View 中:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Category)
</td>
</tr>
我认为框架会自动使用 DisplayName 属性。似乎很奇怪它没有。但是无所谓。试图通过扩展来克服这个问题(在同一问题的另一个线程中找到这个)...
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
public static class EnumExtensions
{
public static string GetDisplayName(this Enum enumValue)
{
return enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.GetName();
}
}
看起来它应该可以工作,但是当我尝试使用它时:
@Html.DisplayFor(modelItem => item.Category.GetDispayName())
我收到这个错误:
{"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."}
最佳答案
您可能要考虑的一件事是为枚举添加一个 DisplayTemplate,您的 @Html.DiplayFor()
将使用它。
如果您在 ~/Views/Shared
文件夹中创建一个名为 DisplayTemplates
的文件夹,请添加一个名为 Enum.cshtml 的新 View 并将此代码添加到 View 中
@model Enum
@{
var display = Model.GetDisplayName();
}
@display
然后您所要做的就是在其他 View 中使用 @Html.DisplayFor(modelItem => item.Category)
。
顺便说一句,如果没有 description 属性,您的 GetDisplayName
代码将抛出错误,因此您可能需要使用类似
public static string GetDisplayName(this Enum enumValue)
{
Type type = enumValue.GetType();
string name = Enum.GetName(type, enumValue);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr =
Attribute.GetCustomAttribute(field,
typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return name;
}
关于c# - 枚举显示名称 : Templates can be used only with field access,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32910067/