代码之家  ›  专栏  ›  技术社区  ›  Alex

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

  •  3
  • Alex  · 技术社区  · 15 年前

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

    在我的主要目标中:

    public class MainObject
    {
        public Filter filter;
    }
    

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

    1 回复  |  直到 15 年前
        1
  •  1
  •   Darin Dimitrov    15 年前

    两句话:

    • 您尝试验证的实例需要通过modelbinder才能工作

    我认为第一句话不需要太多解释:

    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