嵌套模式和验证类与ASP.NET MVC 2.0支持 [英] Support for nested model and class validation with ASP.NET MVC 2.0

查看:170
本文介绍了嵌套模式和验证类与ASP.NET MVC 2.0支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图验证含有使用System.ComponentModel.DataAnnotations属性的验证规则其他对象的模型,希望默认MVC实现就足够了:

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.
}

的对象由原始类型,而且还包含其他类也使用DataAnnotications。像这样:

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; }
}

问题是,ASP.NET MVC的验证仅下降1级,只有评估顶级类的属性,可以在digitallycreated.net/Blog/54/deep-inside-asp.net-阅读MVC-2-模型元数据和验证。

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.

有谁知道一个优雅的解决呢?我试过XVAL,但他们似乎使用非递归模式(<一个href=\"http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/\">http://blog.stevensanderson.com/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/).

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/).

有人以前一定正确碰到这个问题?模型中的嵌套的对象似乎不那么奇怪,如果你正在设计一个Web服务。

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.

推荐答案

我建议寻找到流利的验证从codePLEX。验证规则包含在一个单独的类(类似的方式NHibernate和流利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.

`

public class MaintainCompanyViewModelValidator : AbstractValidator<MaintainCompanyViewModel>
    {
        public MaintainCompanyViewModelValidator()
        {
            RuleFor(model => model.Company.ShortName)
                .NotEmpty();
        }

`

这篇关于嵌套模式和验证类与ASP.NET MVC 2.0支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆