Ok, I have a ViewModel that looks like this:
public class UserLogin
{
[Required]
public string EmailAddress { get; set; }
[Required]
public string Password { get; set; }
}
My controller looks like this:
[HttpPost]
public ActionResult LogIn(UserLogin model)
{
if (!ModelState.IsValid)
{
// ...
}
}
My view looks like this:
<% Html.BeginForm("Join", "User", FormMethod.Post); %>
<%= Html.Hidden("ReturnUrl", Request.Url.AbsolutePath) %>
<%= Html.TextBoxFor(c => c.EmailAddress, new { id = "join-emailaddress", @class = "text", uiHintText = "Email address" })%>
<%= Html.ValidationMessageFor(c => c.EmailAddress, "*") %>
<%= Html.PasswordFor(c => c.Password, new { id = "join-password", @class = "text", uiHintText = "Password" })%>
<%= Html.ValidationMessageFor(c => c.Password, "*")%>
<%= Html.PasswordFor(c => c.PasswordConfirm, new { id = "join-password-confirm", @class = "text", uiHintText = "Password (repeat)" })%>
<%= Html.ValidationMessageFor(c => c.PasswordConfirm, "*")%>
<input type="submit" value="Sign me up!" class="submit" />
<% Html.EndForm(); %>
If I post the form with nothing entered in any of the fields, I consistently get a value of ‘true’ for ‘ModelState.IsValid’.
Shouldn’t it be ‘false’, since I’ve marked those fields as ‘Required’ and not entered any values?
Have a look at the latest RC for ASP.NET MVC. It includes some fixes for this.
http://haacked.com/archive/2010/02/04/aspnetmvc2-rc2.aspx
Specifically, from the release notes:
For more information about this change, see the following posting on Brad Wilson’s blog:
Input Validation vs. Model Validation in ASP.NET MVC
http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html