MVC 5.1 Razor DisplayFor not working with Enum DisplayName

后端 未结 1 1537
迷失自我
迷失自我 2020-12-01 05:03

I have the following entity (domain) object and model that contain an enum. The display name appears correctly and works for a EnumDropdownList but for some reason not for t

相关标签:
1条回答
  • 2020-12-01 05:42

    Create new folder Views/Shared/DisplayTemplates
    Add empty Partial View named Enum, to the folder
    Replace Enum View code with:

    @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)
    }
    

    Here is the link to detailed article by Shahriar Hossain

    0 讨论(0)
提交回复
热议问题