我正在使用VS 2010 RTM並嘗試使用MetadataTypeAttribute對簡單類型執行一些基本驗證。當我把驗證屬性放在主類上時,一切正常。但是,當我把它放在元數據類上時,它似乎被忽略了。我一定會錯過一些微不足道的東西,但我現在一直在困擾着這個問題。使用驗證程序時忽略.NET 4 RTM MetadataType屬性
我看過企業庫驗證塊作爲解決方法,但它不支持驗證開箱即用的單個屬性。有任何想法嗎?
class Program
{
static void Main(string[] args)
{
Stuff t = new Stuff();
try
{
Validator.ValidateProperty(t.X, new ValidationContext(t, null, null) { MemberName = "X" });
Console.WriteLine("Failed!");
}
catch (ValidationException)
{
Console.WriteLine("Succeeded!");
}
}
}
[MetadataType(typeof(StuffMetadata))]
public class Stuff
{
//[Required] //works here
public string X { get; set; }
}
public class StuffMetadata
{
[Required] //no effect here
public string X { get; set; }
}
感謝您的代碼! – aikeru 2012-08-23 17:33:16
爲什麼在MSDN的MetadataTypeAttribute列表中沒有註明這一點?我已經掛了幾個小時b/c在我的MVC項目一切工作正常,但是當創建我的Windows應用程序時,我需要解釋 – 2015-11-03 17:37:20