I want to pass an error login notification in the view which I coded my self, but I do not know how. I want to put it in the @Html.ValidationMessageFor(model => model.UserName)
and @Html.ValidationMessageFor(model => model.Password)
or a separate label (am I correct that I will use @Html.ValidationMessage()
instead of @Html.ValidationMessageFor()
?)
here is my model:
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; }
}
here is my controller:
[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
}
here is my view:
@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>
}
You can add the custom error message to the Model state dictionary using the AddModelError
method. The validationSummary
/ValidationMessageFor
helper methods reads the validation errors from model state dictionary when it gets called.
The first parameter is the key for the error message. If you pass string.empty
as the value the custom error message you are passing will be rendered by the ValidationSummary
helper method
ModelState.AddModelError(string.Empty,"Incorrect user name or password.");
return View(p);
If you want to render the error message by the input element (The one ValidationMessageFor
renders), you may pass the property name as the key value when calling the AdddModelError
method.
ModelState.AddModelError(nameof(User.Password),"Incorrect password");
return View();