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