我想在視圖中傳遞一個錯誤登錄通知,我編碼了自己,但我不知道如何。我希望把它放在@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>
}