2017-10-20 124 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(); 
相关问题