2010-10-18 147 views
2

我有下面的類複雜的數據驗證使用數據註釋

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 
} 

我的問題是,當我編輯的聯繫對象,ModelState.IsValid是總是假的。這是由於ContactType中的名稱爲Null,它具有正確的ID。這是因爲ContactType是通過下拉選擇選擇的。我不想從ContactType中刪除驗證,因爲在添加新的ContactType對象時需要驗證。任何想法如何解決這個問題?

如果我需要提供更多信息,請留言。

乾杯

+0

你能告訴我們選擇ContractType的下拉控件的標記嗎? – 2010-11-24 13:00:52

回答

0

當您驗證聯繫人,你不應該驗證ContactType財產作爲財產將永遠不會得到妥善的用戶發送。驗證int類型屬性的ContactTypeId應該可以解決此問題,並保持ContactType驗證不變。

我不確定你使用的是什麼數據訪問框架(看起來像EF Code First),但是在EF模型中首先,你可以在通常的導航屬性之上激活外鍵屬性的生成,這使得添加/編輯情況要容易得多(特別是在只傳遞值而不是完整對象的網絡中)。