我正在使用ASP.NET MVC 5实体框架.在我的视图中,我有一个下拉菜单,我想要做的是使用枚举来填充下拉菜单.这就是我在课堂上得到的:
public enum occupancyTimelineTypes : int
{
TwelveMonths = 12,
FourteenMonths = 14,
SixteenMonths = 16,
EighteenMonths = 18
}
Run Code Online (Sandbox Code Playgroud)
还有这个:
[DisplayName("Occupancy Timeline")]
[Required]
public string occupancyTimeline { get; set; }
public occupancyTimelineTypes occupancyTimelineType
{
get
{
return Enum.Parse(typeof(occupancyTimelineTypes), occupancyTimeline);
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,我收到一个错误,我不知道如何解决:
无法隐式地将类型"对象"转换为存在显式转换(您是否错过了转换?)
我正在填充我的下拉菜单:
@Html.DropDownListFor(model => model.occupancyTimeline,Model.occupancyTimelineType.ToSelectList());
Run Code Online (Sandbox Code Playgroud)
这是我的ToSelectList()方法
public static class MyExtensions
{
public static SelectList ToSelectList(this occupancyTimelineTypes enumObj)
{
var values = from occupancyTimeline e in Enum.GetValues(typeof(occupancyTimeline))
select new { Id = e, Name = string.Format("{0} Months", Convert.ToInt32(e)) };
return new SelectList(values, "Id", "Name", enumObj);
}
}
Run Code Online (Sandbox Code Playgroud)
我不能也不会使用Html.EnumDropDownListFor(),因为出现了太多错误,这是一个噩梦,可以解决这些错误.
这必须是 @Html.DropDownListFor
Enum.Parse返回对象(它不是通用的)所以你需要显式地转换你的返回值.使用:
return (occupancyTimelineTypes)Enum.Parse(typeof(occupancyTimelineTypes), occupancyTimeline);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2066 次 |
| 最近记录: |