我有一个枚举
public enum TypeDesc
{
[Description("Please Specify")]
PleaseSpecify,
Auckland,
Wellington,
[Description("Palmerston North")]
PalmerstonNorth,
Christchurch
}
我正在使用 page_Load 上的以下代码将此枚举绑定到下拉列表
protected void Page_Load(object sender, EventArgs e)
{
if (TypeDropDownList.Items.Count == 0)
{
foreach (TypeDesc newPatient in EnumToDropDown.EnumToList<TypeDesc>())
{
TypeDropDownList.Items.Add(EnumToDropDown.GetEnumDescription(newPatient));
}
}
}
public static string GetEnumDescription(Enum 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;
else
return value.ToString();
}
public static IEnumerable<T> EnumToList<T>()
{
Type enumType = typeof(T);
// Can't use generic type constraints on value types,
// so have to do check like this
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>(enumValArray.Length);
foreach (int val in enumValArray)
{
enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
}
return enumValList;
}
我的 aspx 页面使用以下代码进行验证
<asp:DropDownList ID="TypeDropDownList" runat="server" >
</asp:DropDownList>
<asp:RequiredFieldValidator ID="TypeRequiredValidator" runat="server" ControlToValidate="TypeDropDownList" ErrorMessage="Please Select a City" Text="<img src='Styles/images/Exclamation.gif' />"
ValidationGroup="city"></asp:RequiredFieldValidator>
但我的验证是接受“请指定”作为城市名称。如果未选择城市,我想停止用户提交。