我有一个枚举ASP.NET枚举下拉列表验证
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>
但我的验证是接受“请指定”作为城市名称。如果城市未选中,我想停止提交用户。
但我救了我枚举值作为tinyint在我的数据库中。如果我从枚举中删除了“请指定”,它将在我的数据库中为奥克兰节省0,并且我不希望那个 – KillerGearz
好,你可以从1开始枚举1'Auckland = 1' – tsukimi
我做到了这一点,它适用于所有值除“北帕默斯顿”外。通过视觉工作室通过Jscript错误验证码给出如下:Microsoft JScript运行时错误:Sys.WebForms.PageRequestManagerServerErrorException:'TypeDropDownList'有一个SelectedValue是无效的,因为它不存在于项目列表中。 参数名称:值 – KillerGearz