对于EditorTemplate嵌套模式ASP.NET MVC3条件验证 [英] ASP.NET MVC3 Conditional Validation of nested model for EditorTemplate

查看:96
本文介绍了对于EditorTemplate嵌套模式ASP.NET MVC3条件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个视图模型:

Suppose you have a viewModel:

public class CreatePersonViewModel
{
    [Required]
    public bool HasDeliveryAddress {get;set;}

    // Should only be validated when HasDeliveryAddress is true
    [RequiredIf("HasDeliveryAddress", true)]
    public Address Address { get; set; }
}

和模型地址将是这样的:

public class Address : IValidatableObject
{
    [Required]
    public string City { get; set; }
    [Required]        
    public string HouseNr { get; set; }
    [Required]
    public string CountryCode { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string ZipCode { get; set; }
    [Required]
    public string Street { get; set; }

    #region IValidatableObject Members

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        string[] requiredFields;
        var results = new List<ValidationResult>();

        // some custom validations here (I removed them to keep it simple)

        return results;
    }

    #endregion
}

一些建议创建地址一个视图模型,并添加一些自定义的逻辑存在,但我需要的一个实例地址来传递给我的EditorTemplate的地址。

Some would suggest to create a viewmodel for Address and add some custom logic there but I need an instance of Address to pass to my EditorTemplate for Address.

这里的主要问题是,地址的验证我PersonViewModel的验证之前,这样做我不能prevent它。

The main problem here is that the validation of Address is done before the validation of my PersonViewModel so I can't prevent it.

注:该RequiredIfAttribute是一个自定义属性,它不正是我想要的简单类型

推荐答案

本来是一块蛋糕,如果你已经使用 FluentValidation。 NET 代替DataAnnotations或IValidatableObject,限制验证电源在相当复杂的情况:

Would have been a piece of cake if you had used FluentValidation.NET instead of DataAnnotations or IValidatableObject which limit the validation power quite in complex scenarios:

public class CreatePersonViewModelValidator : AbstractValidator<CreatePersonViewModel>
{
    public CreatePersonViewModelValidator()
    {
        RuleFor(x => x.Address)
            .SetValidator(new AddressValidator())
            .When(x => x.HasDeliveryAddress);
    }
}

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

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