I wan't to validate a login form. I just wan't to check if the email field and password field are filled in. If not, an error message should display. I can't get it to work.
My actionresult Login:
[HttpPost]
public ActionResult Login(string email, string password, string returnUrl)
{
if (ModelState.IsValid)
{
try
{
User user = accountDal.GetAllUsers().FirstOrDefault(x => x.Email == email && x.Password == password);
if (user != null)
{
FormsAuthentication.SetAuthCookie(user.Email, false);
Response.Redirect(returnUrl, false);
}
return View();
}
catch
{
return View();
}
}
return View();
}
So as you can see, I check if the ModelState is valid.
Here is my login view:
@model ProjectInvoice.ViewModels.LoginViewModel
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<h3>Login</h3>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</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="Create" />
</p>
}
And my ViewModel:
public class LoginViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "Password")]
public string Password { get; set; }
}
If I use a breakpoint at the if (ModelState.IsValid) it says it is true, while this is not the case. Am I missing something, or am I doing something wrong?