使用数据注释进行复杂数据验证

时间:2010-10-18 15:36:47

标签: validation asp.net-mvc-2 c#-4.0

我有以下课程

public partial class Contact
{
    public Contact()
    {
    }

    #region Primitive Properties

    public virtual int Id { get; set; }

    [Display(ResourceType = typeof(Common), Name = "Person_Name")]
    [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(Common))]
    [StringLength(100, ErrorMessageResourceName = "Incorrect_Field_Length",
        ErrorMessageResourceType = typeof(Common))]
    public virtual string Name { get; set; }

    [Display(ResourceType = typeof(Common), Name = "Telephone_Number")]
    [DataType(DataType.PhoneNumber)]
    [StringLength(100, ErrorMessageResourceName = "Incorrect_Field_Length",
        ErrorMessageResourceType = typeof(Common))]
    [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(Common))]
    public virtual string Telephone { get; set; }

    [Display(ResourceType = typeof(Common), Name = "EmailAddress")]
    [DataType(DataType.EmailAddress)]
    [StringLength(255, ErrorMessageResourceName = "Incorrect_Field_Length",
        ErrorMessageResourceType = typeof(Common))]
    [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(Common))]
    public virtual string Email { get; set; }

    [Display(ResourceType = typeof(Common), Name = "ContactType")]
    public virtual ContactType ContactType { get; set; }

    public virtual Company Company { get; set; }

    #endregion
}

ContactType看起来像这样

public partial class ContactType
{
    #region Primitive Properties

    public virtual int Id { get; set; }

    [Display(ResourceType = typeof(Common), Name = "ContactType_Name")]
    [StringLength(50, ErrorMessageResourceName = "Incorrect_Field_Length",
        ErrorMessageResourceType = typeof(Common))]
    [Required(ErrorMessageResourceName = "Validation_Required", ErrorMessageResourceType = typeof(Common))]
    public virtual string Name { get; set; }

    #endregion
}

我遇到的问题是,当我编辑Contact对象时,ModelState.IsValid始终为false。这是由于ContactType中的Name为Null,它具有正确的id。这是因为通过下拉选择选择了ContactType。我不想在添加新的ContactType对象时从ContactType中删除验证。知道如何解决这个问题吗?

如果我需要提供更多信息,请大声说。

干杯

1 个答案:

答案 0 :(得分:0)

验证Contact时,不应验证ContactType属性,因为该属性永远不会被用户正确发送。验证int type属性的ContactTypeId应解决此问题,并使ContactType验证保持不变。

我不确定您使用的是哪种数据访问框架(看起来像EF Code First),但在EF Model First中,您可以在通常的导航属性之上激活外键属性的生成,从而实现添加/编辑方案更容易(特别是在你只传递值而不是完整对象的网页上)。