Two points:
- Use public properties, not fields on models.
- The instance you are trying to validate must go through the model binding in order for this to work
, :
public class Filter
{
[StringLength(5)]
public String Text { get; set; }
}
public class MainObject
{
public Filter Filter { get; set; }
}
, , :
public ActionResult Index()
{
MainObject mo = GoFetchMainObjectSomewhere();
bool isValid = TryValidateModel(mo);
return View();
}
, :
public ActionResult Index(MainObject mo)
{
bool isValid = TryValidateModel(mo);
return View();
}
, :
public ActionResult Index(MainObject mo)
{
bool isValid = ModelState.IsValid;
return View();
}
: TryValidateModel.