如何将自定义登录失败通知传递给MVC4中的视图

时间:2017-10-20 14:20:07

标签: asp.net-mvc-4 validationmessage

我想在我编码自己的视图中传递错误登录通知,但我不知道如何。我想将其放在@Html.ValidationMessageFor(model => model.UserName)@Html.ValidationMessageFor(model => model.Password)或单独的标签中(我是否更正我会使用@Html.ValidationMessage()代替@Html.ValidationMessageFor()?)

这是我的模特:

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

2 个答案:

答案 0 :(得分:1)

您可以使用AddModelError方法将自定义错误消息添加到Model状态字典中。 validationSummary / ValidationMessageFor辅助方法在调用时从模型状态字典中读取验证错误。

第一个参数是错误消息的键。如果您传递string.empty作为值,则您传递的自定义错误消息将由ValidationSummary帮助程序方法呈现

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

如果要通过input元素(一个ValidationMessageFor渲染)呈现错误消息,则可以在调用AdddModelError方法时将属性名称作为键值传递。

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

答案 1 :(得分:0)

我们可以使用AddModelError方法来处理自定义错误消息

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