[英]Display enum in dropdown with Html.DropdownListFor
in a model file I have在我的模型文件中
public enum Title
{
Ms,
Mrs,
Mr
}
I would like to display on the register form's downdown box these selectable values.我想在注册表单的下拉框中显示这些可选值。
But I don't know how.但我不知道怎么办。 It doesn't necessarily require me to use an enum, provided those titles could be in use with
dropdownlistfor
, please you can suggest me any methods.它不一定要求我使用枚举,前提是这些标题可以与
dropdownlistfor
一起使用,请你给我建议任何方法。 Thank you.谢谢你。
you can bind it like this 你可以像这样绑定它
ddl.DataSource = Enum.GetNames(typeof(Title));
ddl.DataBind();
if you want to get the selected value as well do the following 如果您想获得所选值,请执行以下操作
Title enumTitle = (Title)Enum.Parse(ddl.SelectedValue);
There are a couple of methods to this. 有几种方法可以解决这个问题。
One is to create a method that returns a select list. 一种是创建一个返回选择列表的方法。
private static SelectList ToSelectList(Type enumType, string selectedItem)
{
var items = new List<SelectListItem>();
foreach (var item in Enum.GetValues(enumType))
{
var title = ((Enum)item).GetDescription();
var listItem = new SelectListItem
{
Value = ((int)item).ToString(),
Text = title,
Selected = selectedItem == item.ToString()
};
items.Add(listItem);
}
return new SelectList(items, "Value", "Text");
}
The second method is to create helper method 第二种方法是创建辅助方法
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, string optionLabel, object htmlAttributes)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Type enumType = GetNonNullableModelType(metadata);
IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();
IEnumerable<SelectListItem> items = from value in values
select new SelectListItem
{
Text = GetEnumDescription(value),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
};
// If the enum is nullable, add an 'empty' item to the collection
if (metadata.IsNullableValueType)
{
items = SingleEmptyItem.Concat(items);
}
return htmlHelper.DropDownListFor(expression, items, optionLabel, htmlAttributes);
}
public static string GetEnumDescription<TEnum>(TEnum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if ((attributes != null) && (attributes.Length > 0))
{
return attributes[0].Description;
}
return value.ToString();
}
I use a combination of things. 我使用了一些东西。 First off, here's an extension method for Enums to get all enum items in a collection from an enum type:
首先,这是Enums的一种扩展方法,用于从枚举类型中获取集合中的所有枚举项:
public static class EnumUtil
{
public static IEnumerable<T> GetEnumValuesFor<T>()
{
return Enum.GetValues(typeof(T)).Cast<T>();
}
}
Then, I have some code to turn a List into a List. 然后,我有一些代码将List转换为List。 You can indicate which of the values you are passing in are already Selected (just 1 for a Dropdown list, but you can use this to power a CheckBoxList as well), as well has indicating ones to exclude too, if necessary.
您可以指示您传入的值中的哪些已经被选中(只有1用于下拉列表,但您也可以使用它来为CheckBoxList提供动力),并且如果需要,还指示要排除的值。
public static List<SelectListItem> GetEnumsByType<T>(bool useFriendlyName = false, List<T> exclude = null,
List<T> eachSelected = null, bool useIntValue = true) where T : struct, IConvertible
{
var enumList = from enumItem in EnumUtil.GetEnumValuesFor<T>()
where (exclude == null || !exclude.Contains(enumItem))
select enumItem;
var list = new List<SelectListItem>();
foreach (var item in enumList)
{
var selItem = new SelectListItem();
selItem.Text = (useFriendlyName) ? item.ToFriendlyString() : item.ToString();
selItem.Value = (useIntValue) ? item.To<int>().ToString() : item.ToString();
if (eachSelected != null && eachSelected.Contains(item))
selItem.Selected = true;
list.Add(selItem);
}
return list;
}
public static List<SelectListItem> GetEnumsByType<T>(T selected, bool useFriendlyName = false, List<T> exclude = null,
bool useIntValue = true) where T : struct, IConvertible
{
return GetEnumsByType<T>(
useFriendlyName: useFriendlyName,
exclude: exclude,
eachSelected: new List<T> { selected },
useIntValue: useIntValue
);
}
And then in my View Model, when I need to fill a DropdownList, I can just grab the List from that helper method like so: 然后在我的View Model中,当我需要填充DropdownList时,我可以从那个帮助器方法中获取List,如下所示:
public class AddressModel
{
public enum OverrideCode
{
N,
Y,
}
public List<SelectListItem> OverrideCodeChoices { get {
return SelectListGenerator.GetEnumsByType<OverrideCode>();
} }
}
A little late but you can just use the Html helpers:有点晚了,但你可以只使用 Html 助手:
@Html.GetEnumSelectList<Title>()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.