2015-09-11 14 views
2

我正在開發一個MVC 5應用程序並使用內置的AccountController用戶註冊方法。由於我需要,我在RegisterViewModel中添加了用戶名屬性。現在我想在用戶名屬性中添加遠程驗證,以便在用戶名重複時立即提示用戶。如何在MVC中的一種方法中使用遠程和比較屬性

但是,當我嘗試遠程驗證,並添加System.Web.Mvc參考,比較口令屬性和確認密碼開始給錯誤。

我經歷了一些在線學習,得到了那個System.Web.Mvc也得到了一個Compare方法,並且添加了一個這個類的引用,讓編譯器比較了一下方法。

我RegisterViewModel是:

public class RegisterViewModel 
    { 
     [Required] 
     [EmailAddress] 
     [Display(Name = "Email")] 
     public string Email { get; set; } 


     [Required] 
     [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 
     [DataType(DataType.Password)] 
     [Display(Name = "Password")] 
     public string Password { get; set; } 

     [DataType(DataType.Password)] 
     [Display(Name = "Confirm password")] 
     [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 
     public string ConfirmPassword { get; set; } 

     [Required] 
     [Display(Name = "User Name")] 
     [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")] 
     [Remote("DuplicateUserName", "Account", ErrorMessage = "UserName already exists.")] 
     public string UserName { get; set; } 

    } 

它給的錯誤是:

'CompareAttribute' 是 'System.ComponentModel.DataAnnotations.CompareAttribute' 和 之間不明確的引用'System.Web.Mvc.CompareAttribute'

現在我不能刪除引用使用System.ComponentModel.DataAnnotations類,因爲我使用該類的必需和顯示屬性。但我也想添加遠程驗證。我該怎麼做?

+1

只需添加命名空間'[System.ComponentModel.DataAnnotations.Compare(「Password」...' –

+0

我正在觀察相當奇怪的情況..我的遠程驗證沒有打破AccountController ...但是當我將控制器更改爲其他..它打破了很好.. –

+0

不知道你說什麼:)。 (你是什麼意思_breaking_?)你需要問一個更好的解釋和相關的代碼 –

回答

2

完整的命名空間添加到attrubute

[System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 
public string ConfirmPassword { get; set; } 

或者,你可以別名添加到您的usings

using Remote = System.Web.Mvc.RemoteAttribute; 
+0

我正在觀察相當奇怪的情況..我的遠程驗證沒有打破AccountController ...但是當我將控制器更改爲其他..它打破了很好.. –

2

你可以給的完整路徑的屬性,例如:

[System.Web.Mvc.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 
public string ConfirmPassword { get; set; } 
相關問題