支持 ASP.NET MVC 2.0 的嵌套模型和类验证
我正在尝试使用 System.ComponentModel.DataAnnotations 属性来验证包含具有验证规则的其他对象的模型,希望默认的 MVC 实现就足够了:
var obj = js.Deserialize(json, objectInfo.ObjectType);
if(!TryValidateModel(obj))
{
// Handle failed model validation.
}
该对象由原始类型组成,但也包含也使用 DataAnnotations 的其他类。像这样:
public class Entry
{
[Required]
public Person Subscriber { get; set; }
[Required]
public String Company { get; set; }
}
public class Person
{
public String FirstName { get; set;}
[Required]
public String Surname { get; set; }
}
问题是 ASP.NET MVC 验证仅下降 1 级,并且仅评估顶级类的属性,如可以在 digitallycreated.net/Blog/54/deep-inside-asp.net- 上阅读mvc-2-模型元数据和验证。
有谁知道一个优雅的解决方案吗?我尝试过 xVal,但它们似乎使用非递归模式(http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/)。
以前一定有人遇到过这个问题吧?如果您正在设计 Web 服务,那么在模型中嵌套对象似乎并不那么奇怪。
I'm trying to validate a model containing other objects with validation rules using the System.ComponentModel.DataAnnotations attributes was hoping the default MVC implementation would suffice:
var obj = js.Deserialize(json, objectInfo.ObjectType);
if(!TryValidateModel(obj))
{
// Handle failed model validation.
}
The object is composed of primitive types but also contains other classes which also use DataAnnotications. Like so:
public class Entry
{
[Required]
public Person Subscriber { get; set; }
[Required]
public String Company { get; set; }
}
public class Person
{
public String FirstName { get; set;}
[Required]
public String Surname { get; set; }
}
The problem is that the ASP.NET MVC validation only goes down 1 level and only evaluates the properties of the top level class, as can be read on digitallycreated.net/Blog/54/deep-inside-asp.net-mvc-2-model-metadata-and-validation.
Does anyone know an elegant solution to this? I've tried xVal, but they seem to use a non-recursive pattern (http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/).
Someone must have run into this problem before right? Nesting objects in your model doesn't seem so weird if you're designing a web service.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议从 codeplex 中研究 Fluent Validation。验证规则包含在一个单独的类中(类似于 NHibernate 和 Fluent NHibernate 的工作方式)。使用 lambda 来指定要验证的属性,支持子属性。
`
`
I suggest looking into Fluent Validation from codeplex. The validation rules are contained in a separate class (similar to the way NHibernate and Fluent NHibernate work). One uses a lambda to specify the property to validate, supporting child properties.
`
`