gpt4 book ai didi

c# - MVC 5.1 Razor DisplayFor 不使用 Enum DisplayName

转载 作者:IT王子 更新时间:2023-10-29 04:05:51 25 4
gpt4 key购买 nike

我有以下包含枚举的实体(域)对象和模型。显示名称正确显示并适用于 EnumDropdownList 但由于某些原因不适用于 DisplayFor 帮助程序,所有显示的都是实际的枚举名称。

不确定我遗漏了什么,asp.net MVC 5.1 为此添加了显示名称支持,因此我不需要创建自己的辅助方法。请参阅:https://aspnet.codeplex.com/SourceControl/latest#Samples/MVC/EnumSample/EnumSample/Models/Enums.cs

public class Addon
{
public int Id { get; set; }
public AddonType AddonType { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public bool IsActive { get; set; }
}

public enum AddonType : byte
{
[Display(Name = "Cake Theme")]
CakeTheme,
[Display(Name = "Cake Flavour")]
CakeFlavour,
[Display(Name = "Cupcake Icing")]
CupcakeIcing,
[Display(Name = "Party Addon")]
AddOn
}

型号

public class AddonModel
{
public int Id { get; set; }
public AddonType AddonType { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public bool IsActive { get; set; }
}

查看

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>Type</th>
<th>Name</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(model => item.AddonType)
</td>
<td>
@Html.DisplayFor(model => item.Name)
</td>
<td>
@Html.DisplayFor(model => item.Price)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}

</table>

最佳答案

创建新文件夹 Views/Shared/DisplayTemplates
将名为 Enum 的空局部 View 添加到文件夹
将枚举 View 代码替换为:

@model Enum

@if (EnumHelper.IsValidForEnumHelper(ViewData.ModelMetadata))
{
// Display Enum using same names (from [Display] attributes) as in editors
string displayName = null;
foreach (SelectListItem item in EnumHelper.GetSelectList(ViewData.ModelMetadata, (Enum)Model))
{
if (item.Selected)
{
displayName = item.Text ?? item.Value;
}
}

// Handle the unexpected case that nothing is selected
if (String.IsNullOrEmpty(displayName))
{
if (Model == null)
{
displayName = String.Empty;
}
else
{
displayName = Model.ToString();
}
}

@Html.DisplayTextFor(model => displayName)
}
else
{
// This Enum type is not supported. Fall back to the text.
@Html.DisplayTextFor(model => model)
}

这是 link to detailed article by Shahriar Hossain

关于c# - MVC 5.1 Razor DisplayFor 不使用 Enum DisplayName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24334761/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com