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

标签 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 中的“文本”长度超过 5 个字符,验证仍然有效。

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

最佳答案

两点说明:

  • 使用模型上的公共(public)属性而不是字段
  • 您尝试验证的实例需要通过模型绑定(bind)器才能正常工作

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

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

关于asp.net-mvc - 子对象上的 ASP.NET MVC 2 模型验证 (DataAnnotations),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3218017/

相关文章:

asp.net-mvc - 如何知道在 ASP.NET 中将多个文件上传到 azure 存储 blob 何时完成

c# - MVC HttpPost 属性不起作用

ruby-on-rails - 重定向后的验证消息

javascript - 有没有办法验证 Joi 模式中的动态键名?

Java 特定客户类型

asp.net-mvc-2 - ASP.NET MVC - 简单面包屑(站点地图)

c# - 为管理员用户角色呈现未 bundle 的 Assets

asp.net-mvc - View() 与 PartialView()

asp.net-mvc - asp.net mvc - MicrosoftMvcAjax.js 在 IE8 中更新表元素时抛出 javascript 错误

c# - Orchard 项目模块出现错误 : No persister for: SomePartRecord