[HttpPost]
public ActionResult Login(LoginModel model)
{
if (ModelState.IsValid)
{
Authenticate(model.Username, model.Password);
return RedirectToAction("Index");
}
else
{
return View(model);
}
}
private void Authenticate(string userName, string password)
{
const string commaSeperatedRoles = "Administrator,Editor";
if (userName == "xx" && password == "xxx")
{
FormsAuthenticationUtil.RedirectFromLoginPage(userName, commaSeperatedRoles, false);
}
}
and LoginModel
public class LoginModel
{
[Required(ErrorMessage="*")]
[StringLength(10)]
public string Username { get; set; }
[Required(ErrorMessage = "*")]
[StringLength(10)]
public string Password { get; set; }
}
and view
@using (Html.BeginForm())
{
<table width="100%">
<tr>
<td>Username:</td>
<td>
@Html.TextBoxFor(m => m.Username, new { @style = "width: 140px;" })
</td>
</tr>
<tr>
<td>Passwd:</td>
<td>
@Html.PasswordFor(m => m.Password, new { @style = "width: 140px;" })
</td>
</tr>
</table>
<div class="napaka">Wrong username and password</div>
<br />
<input type="submit" class="button" value="Login" />
}
but now i always get this message of wrong login “Wrong username and password”. How can i write this message only when username and password are wrong? I am using mvc3 in C#. Can i somehow send bool variable to view or what is the sbet way?
In case of wrong credentials add an error message to the model state:
and in the view instead of hardcoding the error message in a div use the ValidationSummary helper: