I am building an generic SelectListItem to be used with a dropdown. Trying to cast an Enum of type T to its type , but Iam missing something. LocalizedStringKeyFor complains that its getting two parameters but as I sees it ((typeof(T))status) is just one parameter????
public static SelectListItem BuildSelectListItem<T>(T status, T? selected) where T : struct, Enum
{
var pretext = LocalizedString.Get(LocalizedStringKeyHelper.LocalizedStringKeyFor((typeof(T))status));
return new SelectListItem()
{ Text = pretext, Value = ((int)Convert.ChangeType(status, typeof(T))).ToString(), Selected = selected.HasValue && EqualityComparer<T>.Default.Equals(status, selected.Value) };
}
Actually you do give "two" different parameters to LocalizedStringKeyFor You pass typeof(T) "and" status (missing some comma's but ok).
I think you're kind of looking for a helper function like below; where you pass your "T" (as enum) as the enumerator and the "selected" as parameter.
public static string LocalizedStringKeyFor<T>(T? selected) where T : struct, Enum
{
return "Not a clue";
}
public static IEnumerable<SelectListItem> BuildSelectList<T>(T? selected) where T : struct, Enum
{
var values = new List<SelectListItem>();
foreach (T type in (T[])Enum.GetValues(typeof(T)))
{
values.Add(new SelectListItem()
{
Text = LocalizedStringKeyFor<T>(type),
Value = Convert.ToInt32(type).ToString(),
Selected = selected == null ? false : selected.GetValueOrDefault().Equals(type)
});
}
return values;
}
In the method above I don't have a clue what your LocalizedStringKeyFor does, so that's the answer "Not a clue" - but it uses your enum as T for listing all options and marking the "selected?" as selected option. If there is no selected present your first option will default to selected.
You want to pass your enum value as an int, therefor the Int32 conversion and beware that this method does not work with flagged enums (or at least combined flagged enums).
UPDATE: How to use;
You can use this function for instance like so (where Model.Role is of course your enum)
@Html.DropDownListFor(m => m.Role, _dropdownLists.BuildSelectListItem<Contracts.Roles>(Model.Role), new { @class = "form-control" })