默认ModelValidater覆盖MVC自定义验证属性。值“null”无效

时间:2012-04-20 11:54:05

标签: asp.net-mvc validation

我有一个带有一些bool对象的模型

    [DisplayName("Is student still at school")]
    //[ValidBoolDropDown("IsStillAtSchool")]
    public bool? IsStillAtSchool { get; set; }

正在使用一些bool编辑器下拉模板实现

    @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'对学生来说是无效的。(又名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还是有其他事情发生的情况

感谢Adavance

1 个答案:

答案 0 :(得分:1)

好的,问题出在该行

的下拉模板中
  @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 })

new SelectListItem(){Text =&#34; Select&#34;,Value =&#34; null&#34;,Selected = Model == null? true:false}

成为问题Selectlistitem

当默认模型绑定器尝试将表单数据绑定回模型时,字符串&#34; null&#34;不等于null(空对象)

一旦更改为

new SelectListItem() { Text = "Select", Value = ""}

一切都很愉快,验证attrribute可以完成它的工作

感谢

ASP.NET MVC: DropDownList validation

:d