【问题标题】:Can ASP.Net MVC 2 Custom attributes on class level and on property level be active in the same time?类级别和属性级别的 ASP.Net MVC 2 自定义属性可以同时处于活动状态吗?
【发布时间】:2011-12-08 19:09:15
【问题描述】:

我正在开发 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 有另一个键(即“”)。我知道优势有属性属性,然后是类属性。我的问题;有没有办法同时获取所有验证消息,无论涉及哪种属性(类或属性属性)?提前致谢。

【问题讨论】:

    标签: c# asp.net-mvc-2 data-annotations custom-attributes modelstate


    【解决方案1】:

    如果存在属性级别验证错误,ASP.NET MVC 将不会执行类级别验证。 Brad Wilson 在他的blog post 中解释了这一点:

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多