How can I check the nested model?

Problem:
I am trying to test a nested model, but the data annotation attribute is not executed when an instance of the nested model is created.

public class Model
{
    [Required]
    string MainTitle {get;set;}

    public NestedModel NestedModel { get; set; }
}
public class NestedModel
{
    [Required]
    string SubTitle {get;set;}
}

In the controller:

public ActionResult GetTitles(Model model)
{
    if(ModelState.IsValid)
    {
       //Submodel is always valid even if the sub-title is null.
    }
}

Doesn't support Mvc4? How to extend verification to work with this aspect?

+4
source share
1 answer

I had the same problem. I ended up with this:

public ActionResult GetTitles(Model model)
{
    if(ModelState.IsValid && TryValidateModel(model.NestedModel, "NestedModel."))
    {
       //Submodel will be validated here.
    }
}
+7
source

All Articles