Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate nested model?

Problem:
I trying to validate the nested Model but the data annotation attribute is not executing when the Nested Model Instance create.

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

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

At The Controller:

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

Doesn't Mvc4 Support it? How can I extend the validation to work with this aspect?

like image 243
Dvir Avatar asked Oct 01 '13 16:10

Dvir


1 Answers

I had the same problem. I ended doing this:

public ActionResult GetTitles(Model model)
{
    if(ModelState.IsValid && TryValidateModel(model.NestedModel, "NestedModel."))
    {
       //Submodel will be validated here.
    }
}
like image 160
JoeTac Avatar answered Oct 23 '22 08:10

JoeTac