【发布时间】: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