我有一些布爾模型對象MVC自定義驗證屬性被默認ModelValidater..The值「空」改寫無效
[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>
在後我仍然得到默認模型驗證錯誤
值「空」是無效的在校studentstill是。(又名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此屬性仍然未能
我看到一些關於轉動自動required標誌關閉在Glocal.asx
值類型DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
但是這並沒有worked..is它的情況下創建一個自定義MetadataValidatorProvider的應用程序或者是有s^omething別的事情上
感謝Adavance