【问题标题】:ASP.NET MVC 2 Model Validation (DataAnnotations) on Subobject子对象上的 ASP.NET MVC 2 模型验证(DataAnnotations)
【发布时间】:2010-07-10 05:46:41
【问题描述】:
ASP.NET MVC 2 模型验证是否包含子对象?
我有一个实例“过滤器”,来自这个类:
public class Filter
{
[StringLength(5)]
String Text { get; set; }
}
在我的主要对象中:
public class MainObject
{
public Filter filter;
}
但是,当我执行 TryValidateModel(mainObject) 时,即使 MainObject.Filter.Text 中的“文本”超过 5 个字符,验证仍然有效。
这是故意的,还是我做错了什么?
【问题讨论】:
标签:
asp.net-mvc
validation
asp.net-mvc-2
data-annotations
model-validation
【解决方案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。