IValidatableObject未触发

时间:2011-09-21 15:52:41

标签: asp.net-mvc asp.net-mvc-3 model-validation ivalidatableobject

我正在尝试使用此处所述的IValidatableObject http://davidhayden.com/blog/dave/archive/2010/12/31/ASPNETMVC3ValidationIValidatableObject.aspx

但是当我尝试验证时它不会触发,ModelState.IsValid总是true

这是我的型号代码:

[MetadataType(typeof(RegistrationMetaData))]
public partial class Registration : DefaultModel
{
    [Editable(false)]
    [Display(Name = "Property one")]
    public int PropertyOne { get; set; }
}

public class RegistrationMetaData :IValidatableObject
{
    [Required(ErrorMessage = "Customer no. is required.")]
    [Display(Name = "Customer no.")]
    public string CustomerNo { get; set; }

    [Display(Name = "Comments")]
    public string Comments { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (new AccountModel().GetProfile(CustomerNo) == null)
            yield return new ValidationResult("Customer no. is not valid.", new[] { "CustomerNo" });
    }
}

我扩展了一个名为Registration的LINQ to SQL表,我的第一个猜测是,这在Meta类上是不可能的,但我不确定?

我没有收到任何错误,并且构建得很好,但Validate方法不会触发。我错过了什么?

1 个答案:

答案 0 :(得分:2)

那是因为Registration模型应该实现IValidatableObject而不是RegistrationMetaData

[MetadataType(typeof(RegistrationMetaData))]
public partial class Registration : IValidatableObject
{
    [Editable(false)]
    [Display(Name = "Property one")]
    public int PropertyOne { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (new AccountModel().GetProfile(CustomerNo) == null)
            yield return new ValidationResult("Customer no. is not valid.", new[] { "CustomerNo" });
    }
}

public class RegistrationMetaData
{
    [Required(ErrorMessage = "Customer no. is required.")]
    [Display(Name = "Customer no.")]
    public string CustomerNo { get; set; }

    [Display(Name = "Comments")]
    public string Comments { get; set; }
}