2017-10-20 123 views
0

我想在視圖中傳遞一個錯誤登錄通知,我編碼了自己,但我不知道如何。我希望把它放在@Html.ValidationMessageFor(model => model.UserName)@Html.ValidationMessageFor(model => model.Password)或單獨的標籤(我是正確的,我會用@Html.ValidationMessage()代替@Html.ValidationMessageFor()?)如何將自定義登錄失敗的通知傳遞給MVC4中的視圖

這裏是我的模型:

public class User 
{ 
    public int UserId { get; set; } 

    [Required] 
    [Display(Name = "User Name")] 
    public string UserName { get; set; } 

    [Required] 
    [DataType(DataType.Password)] 
    public string Password { get; set; } 
} 

這裏是我的控制器:

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Login(User p) 
{ 
    if (ModelState.IsValid) 
    { 
     User item = db.Authenticate(p); 

     if (item != null) // if item is not null, the login succeeded 
     { 
      return RedirectToAction("Main", "Home"); 
     } 
    } 
    string error = "Incorrect user name or password."; // I don't know how to pass this 
    return View(); //login failed 
} 

這裏是我的看法:

@using (Html.BeginForm()) { 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <legend>User</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.UserName) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.UserName) 
      @Html.ValidationMessageFor(model => model.UserName) 
     </div> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Password) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Password) 
      @Html.ValidationMessageFor(model => model.Password) 
     </div> 

     <p> 
      <input type="submit" value="Login" /> 
     </p> 
    </fieldset> 
} 

回答

1

您可以使用AddModelError方法將自定義錯誤消息添加到模型狀態字典中。幫助器方法在被調用時從模型狀態字典中讀取驗證錯誤。

第一個參數是錯誤消息的關鍵。如果傳遞string.empty作爲要傳遞的自定義錯誤消息將由ValidationSummary輔助方法

ModelState.AddModelError(string.Empty,"Incorrect user name or password."); 
return View(p); 

如果要由所述輸入元件以使錯誤消息(該一個ValidationMessageFor繪製)要呈現的值,就可以在調用AdddModelError方法時,傳遞屬性名稱作爲鍵值。

ModelState.AddModelError(nameof(User.Password),"Incorrect password"); 
return View(); 
0

我們可以用AddModelError方法來處理自定義錯誤消息

ModelState.AddModelError(nameof(User.UserName),"Incorrect UserName"); 
ModelState.AddModelError(nameof(User.Password),"Incorrect password"); 
return View(); 
相關問題