1

我正在开发 asp.net mvc 2 Web 应用程序。我有具有 3 个属性的模型:

[IsCityInCountry("CountryID", "CityID"]
public class UserInfo
{
    [Required]
    public int UserID { get; set; }

    [Required]
    public int CountryID { get; set; }

    [Required]
    public int CityID { get; set; }
}

我有一个“必需的”属性属性和一个类级别的属性:

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class IsCityInCountry : ValidationAttribute
{
    public IsCityInCountry(string countryIDProperty, string cityIDProperty)
    {
        CountryIDProperty = countryIDProperty;
        CityIDProperty = cityIDProperty;
    }
    public string CountryIDProperty { get; set; }
    public string CityIDProperty { get; set; }

    public override bool IsValid(object value)
    {
        var properties = TypeDescriptor.GetProperties(value);

        var countryID = properties.Find(CountryIDProperty, true).GetValue(value);
        var cityID = properties.Find(CityIDProperty , true).GetValue(value);

        int countryIDInt;
        int.TryParse(countryID.ToString(), out countryIDInt);

        int cityIDInt;
        int.TryParse(cityID.ToString(), out cityIDInt);

        if (CountryBusiness.IsCityInCountry(countryIDInt, cityIDInt))
        {
            return true;
        }

        return false;
    }
}

当我在视图上发布表单并且未输入 CountryID 时,在 ModelState 字典中存在关于该问题的错误。其他属性被忽略(“IsCityInCountry”)。当我选择不在所选国家/地区的 CountryID 和 CityID 时,我会收到相应的验证消息,并且 ModelState 有另一个键(即“”)。我知道优势有属性属性,然后是类属性。我的问题; 无论涉及哪种属性(类或属性属性),有什么方法可以同时获取所有验证消息?提前致谢。

4

1 回答 1

1

如果存在属性级别验证错误,ASP.NET MVC 将不会执行类级别验证。布拉德威尔逊在他的博客文章中解释了这一点:

今天早些时候,我们对 MVC 2 进行了更改,将验证系统从输入验证转换为模型验证。

这意味着我们将始终在一个对象上运行所有验证器,如果该对象在模型绑定期间绑定了至少一个值。我们首先运行属性级验证器,如果所有这些都成功,我们将运行模型级验证器。

如果您想在 ASP.NET MVC 应用程序中执行一些更高级的验证,我建议您继续检查FluentValidation.NET 。声明式验证根本不适合高级验证场景。

于 2011-10-16T16:33:38.417 回答