枚举列表的验证消息

问题描述

我在视图模型中具有一个枚举属性,如下所示:

gmailaddress = "youremailadress@gmail.com"
gmailpassword = "7777777"
mailto = "youremailadress@gmail.com"
msg = input("What is your message? \n ")
mailServer = smtplib.SMTP('smtp.gmail.com',587)
mailServer.starttls()
mailServer.login(gmailaddress,gmailpassword)
mailServer.sendmail(gmailaddress,mailto,msg)
print(" \n Sent!")
mailServer.quit()```

ClaimType枚举由值1、2、3和4组成。 在视图中,我具有以下字段。请注意自定义认元素:

        [display(Name = "Claim Type")]
        [required(ErrorMessage = "Please select a claim type")]
        public ClaimType ClaimType { get; set; }

当我将该字段留空并尝试提交时,验证错误消息会显示: 值“”无效。 未达到viewmodel中的自定义错误消息,因为它似乎首先验证该值是否为有效的枚举值。 知道如何显示自定义错误消息吗?

解决方法

不确定Required是否适用于不可为空的值类型,以便像这样在模型中尝试使用可为空的ClaimType

[Display(Name = "Claim Type")]
[Required(ErrorMessage = "Please select a claim type")] 
public ClaimType? ClaimType { get; set; }