2010-10-29 78 views
0

我已經通過使用profile provider來擴展成員資格提供者來實現自定義註冊頁面。我成功註冊了用戶。現在我想驗證註冊頁面的字段。內置註冊頁面包含內置驗證消息。 Bu在我的編碼中,我沒有將模型傳遞給註冊動作,而是傳遞屬性。因此,如果我使用If(ModelState.IsValid),它總是給出真實的,即使我沒有填充任何字段。但是在它拋出異常但不在頁面中顯示錯誤消息。請告訴我我必須做什麼。如何獲取我的驗證消息。在asp.net mvc 2.0中進行modelstate驗證

我看到帳戶模型類中的註冊模型在驗證條件中建立的。因此,我也寫這樣的我的屬性。

由於提前,

公衆的ActionResult放在userRegistration(串名字,字符串姓氏,串登錄ID,串EMAILID,串密碼,串ConfirmPassword) {

 //int id= int.Parse(ViewData["id"] as string); 


      string firstName = FirstName; 
      string lastName = LastName; 
      string userName = LoginId; 
      string email = EmailId; 
      string password = Password; 
      string confirmPassword = ConfirmPassword; 
      if (ModelState.IsValid) 
      { 
      MembershipCreateStatus status = MembershipService.CreateUser(userName, password, email); 
      //MembershipCreateStatus user = Membership.CreateUser(userName, password, email); 
      Roles.AddUserToRole(userName, "User"); 
      UserProfile.NewUser.Initialize(userName, true); 
      UserProfile.NewUser.FirstName = firstName; 
      UserProfile.NewUser.LastName = lastName; 
      if (status == MembershipCreateStatus.Success) 
      { 
       UserProfile.NewUser.Save(); 

       FormsService.SignIn(userName, false /* createPersistentCookie */); 
       return RedirectToAction("CreateAccountConfirmation"); 
      } 
      else 
      { 
       ModelState.AddModelError("", AccountValidation.ErrorCodeToString(status)); 
      } 

回答

0

的ModelState中是有效的,因爲它不是有一個空白字段無效。

你要麼必須檢查每一個領域中的作用(if (FirstName == null) ModelState.AddModelError("blabla");

或手動(而且我會建議)創建一個視圖模型,並驗證屬性

public class RegistrationModel 
{ 
     [Required] 
     public string FirstName { get; set; } 
     [Required] 
     public string LastName { get; set; } 
     [Required] 
     public string LoginId { get; set; } 
     [Required] 
     public string EmailId { get; set; } 
     [Required] 
     public string Password { get; set; } 
     [Required] 
     public string ConfirmPassword { get; set; } 
} 
+0

嗨Fabino提供它,我(String.IsNullOrEmpty(userName))拋出新的ArgumentException(「Value())如果你告訴它,但它仍然給出真正的錯誤後,它給出如下錯誤 – Mallikarjuna 2010-10-29 11:15:44

+0

公衆MembershipCreateStatus CreateUser(字符串用戶名,字符串密碼,字符串電子郵件) if不能爲空或空白。「,」我們erName「);我必須寫驗證消息也不或 – Mallikarjuna 2010-10-29 11:16:45

+0

這是因爲userName爲空,不是嗎?如果您使用帶有[必填]視圖模型認爲這不應該發生的 – Fabiano 2010-10-29 11:26:02