2015-07-12 45 views
1

我正在開發一個項目,我已經決定實現電子郵件的用戶名並完全放棄默認的MVC用戶名字段。我已經設置了身份登記是這樣的:防止身份提醒被解僱

型號:

[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; } 

控制器設置:

if (ModelState.IsValid) 
     { 
      var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; 
      var result = await UserManager.CreateAsync(user, model.Password); 
      if (result.Succeeded) 
      { ... 

然而,由於這一變化,每當我有這樣一種情況:用戶輸入一個電子郵件已經存在,身份激發用戶名和電子郵件已經存在。

enter image description here

我如何防止在這種情況下被解僱「名稱已被使用」警報?我試圖從「new ApplicationUser」調用中刪除用戶名參數,但是它會向我發出警報,表明它不能爲空。謝謝!

+0

安置自己的模型。 –

+0

@AntarrByrd,貼​​出模特 – user3281114

回答

1

此行AddErrors(result);正在引起問題。 您可以更改方法忽略了「名」

private void AddErrors(IdentityResult result, string[] ignoreStartWith) 
{ 
    foreach (var error in result.Errors) 
    { 
      if (!ignoreStartWith.Any(s => error.StartsWith(s))) 
      { 
       ModelState.AddModelError("", error); 
      } 
    } 
} 

啓動錯誤,並使用它像

AddErrors(result, ignoreStartWith:new[] { "Name" }); 
+0

現貨。非常感謝! – user3281114