我正在尝试制作电话簿的简化版本,但无法在下拉列表中显示区号枚举名称,因此我的模型如下所示:
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>
结果,在城市代码的下拉列表中,我无法准确地得到名字,即不是“一二三”,而是“495,351,812”:
怎么样,告诉我?试图在模型中装饰DataAnnotations,但是没有用。我尝试为模型中的枚举器分配名称,并通过 Enum.GetNames 将其显示在专门的模板中,但它也不起作用

你可以用反射来做这个技巧:
Description让我们从枚举中添加一个属性using System.ComponentModel;要从属性中获取值
Description,可以使用以下方法:重构此方法:
或者可以改写为扩展方法的形式:
重构此方法:
使用:
GetNameFromDescription(CityCode.Three)或CityCode.Three.GetNameFromDescription()结果:
812