枚举.解析不能隐式转换类型'对象'存在显式转换(您是否缺少强制类型转换?)

本文关键字:是否 类型转换 对象 不能 转换 存在 枚举 类型 显式转换 | 更新日期: 2023-09-27 18:07:05

我使用的是ASP。. NET MVC 5实体框架。在我的视图中,我有一个下拉菜单,我要做的是使用枚举来填充下拉菜单。这是我在班上得到的:

    public enum occupancyTimelineTypes : int
    {
        TwelveMonths = 12,
        FourteenMonths = 14,
        SixteenMonths = 16,
        EighteenMonths = 18
    }

:

        [DisplayName("Occupancy Timeline")]
        [Required]
        public string occupancyTimeline { get; set; }
        public occupancyTimelineTypes occupancyTimelineType
        {
            get
            {
                return Enum.Parse(typeof(occupancyTimelineTypes), occupancyTimeline);
            }
        }

我的问题是,我得到一个错误,我不知道如何修复:

不能隐式地将类型"object"转换为显式转换存在(您是否缺少cast?)

我正在填充我的下拉菜单,像这样:

@Html.DropDownListFor(model => model.occupancyTimeline,Model.occupancyTimelineType.ToSelectList());

这是我的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);
        }
    }

我不能也不会使用Html.EnumDropDownListFor(),因为出现了太多的错误,这是一场噩梦,把这些错误放在适当的位置和修复。

必须是@Html.DropDownListFor

枚举.解析不能隐式转换类型'对象'存在显式转换(您是否缺少强制类型转换?)

Enum.Parse返回对象(它不是通用的),所以您需要显式地转换返回值。用途:

return (occupancyTimelineTypes)Enum.Parse(typeof(occupancyTimelineTypes), occupancyTimeline);