我有一个带有一些布尔对象的模型
[DisplayName("Is student still at school")]
//[ValidBoolDropDown("IsStillAtSchool")]
public bool? IsStillAtSchool { get; set; }
正在使用一些布尔编辑器下拉模板实现
@model bool?
@{
int intTabIndex = 1;
if (ViewData["tabindex"] != null)
{
intTabIndex = Convert.ToInt32(ViewData["tabindex"]);
}
}
@{
string strOnChange = "";
if (ViewData["onchange"] != null)
{
strOnChange = ViewData["onchange"].ToString();
}
}
<div class="editor-field">
@Html.LabelFor(model => model):
@Html.DropDownListFor(model => model, new SelectListItem[] { new SelectListItem() { Text = "Yes", Value = "true", Selected = Model == true ? true : false }, new SelectListItem() { Text = "No", Value = "false", Selected = Model == false ? true : false }, new SelectListItem() { Text = "Select", Value = "null", Selected = Model == null ? true : false} }, new { @tabindex = intTabIndex, @onchange = strOnChange })
@Html.ValidationMessageFor(model => model)
</div>
在帖子中,我仍然收到默认模型验证错误
值“null”对于 Is studentstill at school 无效。(又名 IsStillatSchool)
我什至实现了自定义 ValidationAttribute
public class ValidBoolDropDown : ValidationAttribute
{
public ValidBoolDropDown(string dropdownname) :base("Please Select for {0}")
{
DropDownName = dropdownname;
}
private string DropDownName;
protected override ValidationResult IsValid(object value,ValidationContext validationContext)
{
var boolres = GetBool(validationContext);
//if (!boolres.HasValue)
//{
// return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
//}
return ValidationResult.Success;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name);
}
protected bool? GetBool(ValidationContext validationContext)
{
var propertyInfo = validationContext
.ObjectType
.GetProperty(DropDownName);
if (propertyInfo != null)
{
var boolValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
if (boolValue == null)
return null;
return boolValue as bool?;
}
return null;
}
}
这会触发但会被覆盖,并且该属性的 Model.Value.Error 仍然失败
我看到了一些关于在 Glocal.asx 中为值类型关闭自动所需标志的内容
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
但这不起作用..是为应用程序创建自定义 MetadataValidatorProvider 还是有其他事情发生
提前感谢