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?
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.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With