MVC5: Enum radio button with label as displayname

后端 未结 4 1313
梦毁少年i
梦毁少年i 2020-12-30 04:49

I have these enums

public enum QuestionStart
{
    [Display(Name=\"Repeat till common match is found\")]
    RepeatTillCommonIsFound,

    [Display(Name=\"Re         


        
4条回答
  •  庸人自扰
    2020-12-30 05:20

    Here is a solution that uses an extension method and an editor template to create a radio group with a localized name from the display attribute.

    Extension Method

    public static string DisplayName(this Enum enumValue)
    {
        var enumType = enumValue.GetType();
        var memberInfo = enumType.GetMember(enumValue.ToString()).First();
    
        if (memberInfo == null || !memberInfo.CustomAttributes.Any()) return enumValue.ToString();
    
        var displayAttribute = memberInfo.GetCustomAttribute();
    
        if (displayAttribute == null) return enumValue.ToString();
    
        if (displayAttribute.ResourceType != null && displayAttribute.Name != null)
        {
            var manager = new ResourceManager(displayAttribute.ResourceType);
            return manager.GetString(displayAttribute.Name);
        }
    
        return displayAttribute.Name ?? enumValue.ToString();
    }
    

    Example

    public enum IndexGroupBy 
    {
        [Display(Name = "By Alpha")]
        ByAlpha,
        [Display(Name = "By Type")]
        ByType
    }
    

    And here is its usage:

    @IndexGroupBy.ByAlpha.DisplayName()
    

    Editor Template

    Here is an editor template that can be used with the extension method above:

    @model Enum
    
    @{    
        var listItems = Enum.GetValues(Model.GetType()).OfType().Select(e =>
            new SelectListItem
            {
                Text = e.DisplayName(),
                Value = e.ToString(),
                Selected = e.Equals(Model)
            });
        var prefix = ViewData.TemplateInfo.HtmlFieldPrefix;
        var index = 0;
        ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;
    
        foreach (var li in listItems)
        {
            var fieldName = string.Format(CultureInfo.InvariantCulture, "{0}_{1}", prefix, index++);
            
    @Html.RadioButton(prefix, li.Value, li.Selected, new {@id = fieldName}) @Html.Label(fieldName, li.Text)
    } ViewData.TemplateInfo.HtmlFieldPrefix = prefix; }

    And here is an example usage:

    @Html.EditorFor(m => m.YourEnumMember, "Enum_RadioButtonList")
    

提交回复
热议问题