我正在使用以下帮助方法将 MVC (3) selectList 绑定到枚举
public static List<SelectListItem> GetSelectList<T>()
{
Type enumType = typeof(T);
if (!enumType.IsEnum)
throw new ArgumentException("The specified type is not enum");
List<SelectListItem> enumList = new List<SelectListItem>();
var values = Enum.GetValues(enumType);
foreach (var value in values)
{
SelectListItem newItem = new SelectListItem();
newItem.Value = Convert.ToInt32(value).ToString();
newItem.Text = Regex.Replace(Enum.GetName(enumType, value), "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ");
enumList.Add(newItem);
}
return enumList;
}
然后在我的控制器中调用该方法,并将第四个参数作为客户类型的预选 id 传递给 selectList 构造函数。
_view.CustomerTypeSelectList = new SelectList(EnumHelper.GetSelectList<CustomerTypeEnum>(), "Value", "Text", _customer.TypeID);
然后在视图中我绑定了 selectList
<%=Html.DropDownListFor(x => x.CustomerTypeId, Model.CustomerTypeSelectList )%>
但是我无法让 selectList 预填充。
有任何想法吗?