首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类级别和属性级别上的ASP.Net MVC 2自定义属性可以同时激活吗?

类级别和属性级别上的ASP.Net MVC 2自定义属性可以同时激活吗?
EN

Stack Overflow用户
提问于 2011-10-16 16:31:29
回答 1查看 1.1K关注 0票数 1

我正在工作的asp.net mvc 2 web应用程序。我有三种属性的模型:

代码语言:javascript
复制
[IsCityInCountry("CountryID", "CityID"]
public class UserInfo
{
    [Required]
    public int UserID { get; set; }

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

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

我有一个“必需”属性属性,以及类级别上的一个属性:

代码语言:javascript
复制
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有另一个键(即"")。我知道advantage有属性属性,然后是类属性。我的问题是,是否有任何方法同时获得所有验证消息,无论涉及哪种属性(类或属性属性)?提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2011-10-16 16:33:38

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

今天早些时候,我们对MVC 2进行了修改,将验证系统从输入验证转换为模型验证。 这意味着,如果对象在模型绑定期间至少绑定了一个值,那么我们将始终运行对象上的所有验证器。我们首先运行属性级验证器,如果所有这些都成功,我们将运行模型级验证器。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7785676

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档