我正在工作的asp.net mvc 2 web应用程序。我有三种属性的模型:
[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有另一个键(即"")。我知道advantage有属性属性,然后是类属性。我的问题是,是否有任何方法同时获得所有验证消息,无论涉及哪种属性(类或属性属性)?提前谢谢。
发布于 2011-10-16 16:33:38
如果存在属性级验证错误,ASP.NET MVC将不会执行类级验证。布拉德·威尔逊在他的博客帖子中解释了这一点。
今天早些时候,我们对MVC 2进行了修改,将验证系统从输入验证转换为模型验证。 这意味着,如果对象在模型绑定期间至少绑定了一个值,那么我们将始终运行对象上的所有验证器。我们首先运行属性级验证器,如果所有这些都成功,我们将运行模型级验证器。
如果您想在FluentValidation.NET MVC应用程序中执行更高级的验证,我建议您继续检查ASP.NET。声明式验证根本不适合高级验证场景中的要求。
https://stackoverflow.com/questions/7785676
复制相似问题