私は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; }
}
「必須」のプロパティ属性が 1 つと、クラス レベルに 1 つの属性があります。
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 には別のキー ("") があります。アドバンテージにはプロパティ属性とクラス属性があることを理解しています。私の質問; 関連する属性の種類 (クラスまたはプロパティ属性) に関係なく、すべての検証メッセージを同時に取得する方法はありますか? 前もって感謝します。