I am trying to develop an HtmlHelper extension method: EnumDropDownListFor. No matter what I did I was unable to show the selected value. I tried setting Selected=true property of SelectListItem and setting selectedValue of SelectList constructor. While debugging (at return line) I can see Selected=true for the SelectLİstItem which is supposed to be Selected, for both cases. But when I “View Source” none of the options have selected=”selected” attribute.
Where am I going wrong?
Note: Toolkit is my utility class and ToByte is an extension method for Enum
public static MvcHtmlString EnumDropDownListFor<TModel, TProperty>(
this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string optionLabel = null,
object htmlAttributes = null) where TModel : class
{
var selectedValue = helper.ViewData.Model == null
? default(TProperty)
: expression.Compile()(helper.ViewData.Model);
var enumVals = Toolkit.GetEnumValues(typeof(TProperty));
//var selectList = from enumVal in enumVals.OfType<Enum>()
// select new SelectListItem
// {
// Text = enumVal.GetName(),
// Value = enumVal.ToByte().ToString(),
// Selected = Equals(enumVal, Toolkit.To<Enum>(selectedValue))
// };
// helper.ViewData[(expression.Body as MemberExpression).Member.Name] = Toolkit.To<Enum>(selectedValue).ToByte().ToString();
var selectList = new SelectList(from enumVal in enumVals.OfType<Enum>()
select new
{
TextField = enumVal.GetName(),
ValueField = enumVal.ToByte().ToString()
}, "ValueField", "TextField", Toolkit.To<Enum>(selectedValue).ToByte().ToString());
return helper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes);
}
I solved it (:
That was beacuse I am calling “helper.DropDownListFor” with same expression which returns an Enum type and I was trying to set values of options by “Byte” casted values. So it seems that Expression’s return value overrides the given selected value, makes a lot of sense.