我找到的解决方案并没有解决我的问题。我编写了一个自定义验证器,强制用户根据从下拉列表中选择的枚举值填充字段。但是当必填字段为空时,不会显示错误消息。当select为Farmer(枚举字段)时,必须从下拉列表中选择Outreach Person(OutreachPersonId)。
自定义验证器
public class RequiredOutreachOfficerAttribute : ValidationAttribute
{
private CardTypes _cardTypes;
public RequiredOutreachOfficerAttribute(CardTypes cardTypes)
{
_cardTypes = cardTypes;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
CreateBusinessPartnerVM businessPartner = (CreateBusinessPartnerVM)validationContext.ObjectInstance;
if (businessPartner.CardType == _cardTypes && !businessPartner.OutreachPersonId.HasValue)
{
return new ValidationResult("A farmer must have an outreach officer");
}
return ValidationResult.Success;
}
}
模型
[RequiredOutreachOfficer(CardTypes.Farmer, ErrorMessage = "A farmer must have an outreach officer")]
public Guid? OutreachPersonId { get; set; }
查看
<label asp-for="OutreachPersonId">Outreach Officer</label>
@Html.DropDownListFor(m => m.OutreachPersonId, Model.OutreachPersons, "", new { @id = "drpOutreachPersonId", @class = "browser-default" })
<span asp-validation-for="OutreachPersonId" class="text-danger"></span>
似乎自定义验证器有效,因为当我从下拉列表中选择“Farmer”枚举,并且我提交页面时,它会抛出异常;
InvalidOperationException:没有类型的ViewData项 'IEnumerable',其键有'OutreachPersonId'。
但是当我选择另一个不是“Farmer”的输入时,页面成功提交。但我需要验证消息来显示。请帮忙。