繁体   English   中英

MVC 5.1 Razor Display不使用Enum DisplayName

[英]MVC 5.1 Razor DisplayFor not working with Enum DisplayName

我有以下实体(域)对象和包含枚举的模型。 显示名称正确显示并适用于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的空部分视图添加到该文件夹
将Enum 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)
}

以下是Shahriar Hossain详细文章链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM