Search code examples
asp.net-mvcasp.net-mvc-3asp.net-mvc-validation

MVC 3 validation not working for complex model


I have a UserFormModel which contains a UserModel which has a set of properties with the [Required] attribute set. I have read that MVC 3 out of the box will validate models within models by default. However when I submit an empty form in my view passing back a UserFormModel containing an empty UserModel the ModelState.IsValid is always true.

I have tried sending just the UserModel back to my controller and that validates ok. It just seem to be when I am working with complex models that it does not validate.

I have also tried it with the [Required] attribute on the User property within the UserFormModel (which I believe is not required for default behaviour to work) but still no validation takes place.

Any ideas on this one would be much appreciated.

public class UserFormModel
{
    public UserModel User;

    public IEnumerable<SelectListItem> Roles { get; set; }
}

public class UserModel : ModelBase
{       
    [Required]
    public string UserName { get; set; }

    public string Title { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }
}

[HttpPost]
public ActionResult Create(UserFormModel userFormModel)
{
    if (ModelState.IsValid)
    {
        // Do Something
    }
}

Solution

  • You should use properties not fields. So instead of:

    public UserModel User;
    

    you should have:

    public UserModel User { get; set; }
    

    The reason for this is that the default model binder works only with properties.