3

ASP.NET MVC 2模型验证是否包含子对象?Subobject上的ASP.NET MVC 2模型验证(DataAnnotations)

我有一个实例 “过滤器”,从这个类:

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

在我的主要目标:

public class MainObject 
{ 
    public Filter filter; 
} 

然而,当我做TryValidateModel(mainObject)验证仍然有效了甚至如果MainObject.Filter.Text中的“文本”长度超过5个字符。

这是打算,还是我做错了什么?

回答

1

两个备注:

  • 使用公共属性和您的模型并不领域
  • 你正在试图验证需要通过这个模型绑定实例工作

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

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

+0

很好的解释! – 2010-07-26 22:10:19