user979331 user979331 - 2 months ago 18
ASP.NET (C#) Question

Enum.Parse Cannot implicitly convert type 'object' to An explicit conversion exists (are you missing a cast?)

I am using ASP.NET MVC 5 Entity Framework, in My view I have a dropdown menu, what I am trying to is use enum to populate dropdown menus. This is what I 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

Answer

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);