Asp.net mvc 子对象上的ASP.NET MVC 2模型验证(DataAnnotations)

Asp.net mvc 子对象上的ASP.NET MVC 2模型验证(DataAnnotations),asp.net-mvc,validation,asp.net-mvc-2,data-annotations,model-validation,Asp.net Mvc,Validation,Asp.net Mvc 2,Data Annotations,Model Validation,ASP.NET MVC 2模型验证是否包括子对象 我有一个实例“Filter”,来自这个类: public class Filter { [StringLength(5)] String Text { get; set; } } 在我的主要目标中: public class MainObject { public Filter filter; } 但是,当我执行TryValidateModel(mainObject)时,即使mainObject.Filter.Text

ASP.NET MVC 2模型验证是否包括子对象

我有一个实例“Filter”,来自这个类:

public class Filter
{
    [StringLength(5)]
    String Text { get; set; }
}
在我的主要目标中:

public class MainObject
{
    public Filter filter;
}
但是,当我执行TryValidateModel(mainObject)时,即使mainObject.Filter.Text中的“Text”超过5个字符,验证仍然有效

这是故意的,还是我做错了什么?

两条评论:

  • 在模型上使用公共属性而不是字段
  • 您尝试验证的实例需要通过模型绑定才能工作
我认为第一句话不需要太多解释:

public class Filter
{
    [StringLength(5)]
    public String Text { get; set; }
}

public class MainObject
{
    public Filter Filter { get; set; }
}
至于第二个,当它不起作用时:

public ActionResult Index()
{
    // Here the instantiation of the model didn't go through the model binder
    MainObject mo = GoFetchMainObjectSomewhere();
    bool isValid = TryValidateModel(mo); // This will always be true
    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