Использование enum с @ Html .DisplayFor в ASP. NET MVC - PullRequest
0 голосов
/ 23 января 2020

Я использую enum в @Html.DropDownListFor, как показано ниже, и мне интересно, можно ли использовать эти enum при отображении значений, используя их значения id.

Enum:

public enum StatusEnum
{
    [Description("Deleted")]
    Deleted = 0,

    [Description("Active")]
    Active = 1,

    [Description("Passive")]
    Passive= 2
}

EnumHelper:

public static class MyEnumHelper
{
    /// <summary>
    /// For displaying enum descriptions instead of enum names on grid, ddl, etc.
    /// </summary>
    public static string GetDescription<T>(this T enumerationValue)
        where T : struct
    {
        System.Type type = enumerationValue.GetType();
        if (!type.IsEnum)
        {
            throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
        }

        //Tries to find a DescriptionAttribute for a potential friendly name
        //for the enum
        MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
        if (memberInfo != null && memberInfo.Length > 0)
        {
            object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attrs != null && attrs.Length > 0)
            {
                //Pull out the description value
                return ((DescriptionAttribute)attrs[0]).Description;
            }
        }
        //If we have no description attribute, just return the ToString of the enum
        return enumerationValue.ToString();
    }
}

Модель объекта:

public StatusEnum Status { get; set; }

[NotMapped]
public string StatusName
{
    get { return MyEnumHelper.GetDescription(Status); }
}

Вид:

@Html.DropDownListFor(m => m.Status, Enum.GetValues(typeof(UA.Intra.Model.Enum.StatusEnum))
    .Cast<UA.Intra.Model.Enum.StatusEnum>()
    .Select(x => new SelectListItem { Text = x.GetDescription(), Value = x.ToString() }))

I хотите отобразить description с enum с в соответствии с их enum значениями (id). Возможно ли это?

@Html.DisplayFor(m => m.Status)

1 Ответ

0 голосов
/ 23 января 2020

Используйте EnumDropDownFor и отображаемое имя вместо описания.

Пример:

public enum WelcomeMessageType
    {
        [Display(Name = "Prior to accepting Quote")]
        PriorToAcceptingQuote,
        [Display(Name = "After Accepting Quote")]
        AfterAcceptingQuote
    }



@Html.EnumDropDownListFor(model => model.WelcomeMessageType, null, new { @id = "ddlMessageType", @class = "form-control", @style = "width:200px;" })
...