Question

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
    }
}
Was it helpful?

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.

OTHER TIPS

I believe that validation only goes one model property deep in the model. For example if you have the following model

public class Product
{
    public int ProductId { get; set; }
    [Required]
    public int ProductName { get; set; }
    [Required]
    public decimal Price { get; set; }
}

public class ProductViewModel
{
    [Required]
    public Product Product { get; set; }
}

The validation against the product object in the view model will work, the validation against the product class will not with one caveat. If the Product class is a POCO class used in the entity framework code first method, the validation will work against the database. Validation against a view model will only work one deep in my experience.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top