1

Пытаюсь сделать упрощенный вариант телефонного справочника, и у меня не получается отобразить в выпадающем списке имена перечислений кодов городов, то есть моя модель выглядит следующим образом:

using System.ComponentModel.DataAnnotations;
public class User
{
    public string CodeCountry { get; set; }
    public string CodeUser { get; set; }
    public CityCode CodeCity { get; set; }
}
public enum CityCode
{
    [Display(Name = "495")]
    One,
    [Display(Name = "351")]
    Two,
    [Display(Name = "812")]
    Three
}

Контроллер:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        User user = new User();
        user.CodeCountry = "+7";
        user.CodeUser = "123456789";
        user.CodeCity = CityCode.Two;
        return View(user);
    }

}

Вьюшка:

@model MVC_Fund6_1.Models.User
@{
ViewBag.Title = "Home Page";
}
<h2>EditorFor</h2>

@Html.LabelFor(x => x.CodeCountry)<br />
@Html.EditorFor(x => x.CodeCountry) <br />

@Html.LabelFor(x => x.CodeCity)<br />
@Html.EditorFor(x => x.CodeCity,"UserTemplate") <br />

@Html.LabelFor(x => x.CodeUser)<br />
@Html.EditorFor(x => x.CodeUser)

Специализированное представление UserTemplate:

@using MVC_Fund6_1.Models
@model CityCode
<select id="CityCode" name="CityCode">
@foreach (CityCode value in Enum.GetValues(typeof(CityCode)))
{

    <option value="@value">
        @value
    </option>
}
</select>

В итоге я не могу добиться, чтобы в выпадающем списке кодов городов выпадали именно имена, то есть не "One,two,three",а "495,351,812":

введите сюда описание изображения

Как быть, подскажите? Пробовал декорировать DataAnnotations в модели, но не получается. Пробовал присваивать имена перечислителю в модели и в специализированном шаблоне выводить через Enum.GetNames но тоже не получается

0

1 ответ 1

3

Можно провернуть такой трюк с помощью рефлексии:

Добавим в enum атрибут Description из using System.ComponentModel;

public enum CityCode
{
    [Description("495")]
    One,
    [Description("351")]
    Two,
    [Description("812")]
    Three
}

Чтоб получить значение из атрибута Description можно использовать следующий метод:

    static String GetNameFromDescription(Enum enumElement)
    {
        Type type = enumElement.GetType();
        MemberInfo[] memInfo = type.GetMember(enumElement.ToString());
        if (memInfo != null && memInfo.Length > 0)
        {
            Object[] attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes != null && attributes.Length > 0)
                return ((DescriptionAttribute)attributes[0]).Description;
        }
        return enumElement.ToString();
    }

рефакторинг данного метода:

static String GetNameFromDescription(Enum enumElement) => enumElement
        .GetType()
        .GetField(enumElement.ToString())
        .GetCustomAttribute<DescriptionAttribute>()
        .Description;

или можно переписать в форме метода расширения:

    public static String GetNameFromDescription(this Enum enumElement)
    {
        Type type = enumElement.GetType();
        MemberInfo[] memInfo = type.GetMember(enumElement.ToString());
        if (memInfo != null && memInfo.Length > 0)
        {
            Object[] attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes != null && attributes.Length > 0)
                return ((DescriptionAttribute)attributes[0]).Description;
        }
        return enumElement.ToString();
    }

рефакторинг данного метода:

public static String GetNameFromDescription(this Enum enumElement) => enumElement
        .GetType()
        .GetField(enumElement.ToString())
        .GetCustomAttribute<DescriptionAttribute>()
        .Description;

Используем: GetNameFromDescription(CityCode.Three) или CityCode.Three.GetNameFromDescription()

Результат: 812

2
  • 1
    Вау! Вот это круто! спасибо.
    – Mikhail
    9 янв 2019 в 12:22
  • @Mikhail, пожалуйста) не забудьте +1
    – Yaroslav
    9 янв 2019 в 12:45

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.