Reputation: 11861
I am using ASP.NET MVC 5 Entity Framework. In my View I have a dropdown menu and what I am trying to do is use an enum to populate dropdown menus. This is what I've got in my class:
public enum occupancyTimelineTypes : int
{
TwelveMonths = 12,
FourteenMonths = 14,
SixteenMonths = 16,
EighteenMonths = 18
}
and this:
[DisplayName("Occupancy Timeline")]
[Required]
public string occupancyTimeline { get; set; }
public occupancyTimelineTypes occupancyTimelineType
{
get
{
return Enum.Parse(typeof(occupancyTimelineTypes), occupancyTimeline);
}
}
My problem is, I am getting an error I have no idea how to fix:
Cannot implicitly convert type 'object' to An explicit conversion exists (are you missing a cast?)
I am populating my dropdown menu like so:
@Html.DropDownListFor(model => model.occupancyTimeline,Model.occupancyTimelineType.ToSelectList());
and here is my ToSelectList()
Method
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);
}
}
I CANNOT AND WILL NOT USE Html.EnumDropDownListFor()
as too many errors appear and its a nightmare to put in place and fix these errors.
This has to be @Html.DropDownListFor
Upvotes: 1
Views: 4406
Reputation: 27609
Enum.Parse
returns object (it is not generic) so you need to explicitly cast your return value. Use:
return (occupancyTimelineTypes)Enum.Parse(typeof(occupancyTimelineTypes), occupancyTimeline);
Upvotes: 9