0
votes

Suppose I have following models:

Model1:

public class Model1
{
    [Required(ErrorMessageResourceType = typeof (Resource), ErrorMessageResourceName = "RequiredParameter")]
    [Display(Name = "Name", ResourceType = typeof (Resource))]
    public string Name { get; set; }

    [Required(ErrorMessageResourceType = typeof (Resource), ErrorMessageResourceName = "RequiredParameter")]
    [Display(Name = "Description", ResourceType = typeof (Resource))]
    public string Description { get; set; }
    public Model2 Model2 { get; set; }

    public Model1()
    {
        Model2 = new Model2();
    }
}

Model2:

public class Model2
{
    [Required(ErrorMessageResourceType = typeof (Resource), ErrorMessageResourceName = "RequiredParameter")]
    [Display(Name = "Name", ResourceType = typeof (Resource))]
    public string TestValue { get; set; }
}

Controller:

[HttpGet]
public ActionResult TestValidation()
{
    var obj = new Model1();
    return View(obj);
}

[HttpPost]
public ActionResult TestValidation(Model1 obj)
{
    if (ModelState.IsValid)
    {
        return Content("valid");
    }
    return Content("Invalid");
}

When I am trying to validate Model 1 I have strange behavior.

You can see all my properties have string type.

I don't know why model is validated just for First level and not for second level.

If TestValue from Model2 is null I have ModelState.IsValid = true, but if I have Name or description from Model1 with null values I will have ModelState.IsVlaid = false.

Looks like [Required] atribute is working just for first level(Model 1) not and for second level(Model2).

Why do I have this strange behavior?

UPDATE

public class Model1
    {
        [Required]
        public string Name { get; set; }
        [Required]
        public string Description { get; set; }
        public Model2 Model2 { get; set; }

    }

    public class Model2
    {
        [Required]
        public string TestValue { get; set; }                
    }

Using my model like above I am getting validation like expected.Do I need to use like above to get validation working and for Model2 ?

I suspect you are not rendering any controls for property Model2 .TestValue - user3559349
And if not so what this mean?I am rendering textbox for testValue but for testing purposes I deleted it using Shift+CTRL+I . I founded that if I will not initialize object from constructor and If I will put [Required] atribute on Model2 inside Model1 I get and model2 validated how it should be, but I am not shure if this should be like this , I will update my question so you can take a look at this. - Nic