手動驗證對象時,無法獲取compare屬性。我製作了一個簡單的測試控制檯應用程序,它也不起作用。我有什麼不對嗎?比較屬性DataAnnotations不起作用
我使用最新版本的.Net Framework 4.5.1。 我做了這個控制檯測試應用程序,因爲它也不在我的MVC應用程序中執行業務層(單獨類庫)中的數據註釋。
謝謝。
要測試的類:
public class Change // : IValidatableObject
{
/// <summary>
/// The current password of this account.
/// </summary>
[Required(ErrorMessage = "Huidig wachtwoord is verplicht")]
[DataType(DataType.Password)]
public string CurrentPassword { get; set; }
/// <summary>
/// The new password for the logged in user account.
/// </summary>
[Required(ErrorMessage = "Wachtwoord is verplicht")]
[DataType(DataType.Password)]
public string NewPassword { get; set; }
/// <summary>
/// This must be the same as <see cref="NewPassword"/>.
/// </summary>
[Required(ErrorMessage = "Bevestig wachtwoord is verplicht")]
[Compare("NewPassword")]
[DataType(DataType.Password)]
public string NewPassword2 { get; set; }
//public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
//{
// return new List<ValidationResult>();
//}
}
控制檯應用程序:
class Program
{
static void Main(string[] args)
{
var change = new Change()
{
CurrentPassword = "ABC",
NewPassword = "123",
NewPassword2 = "12345678"
};
Console.WriteLine("Initial values:");
Console.WriteLine("NewPassword: " + change.NewPassword);
Console.WriteLine("NewPassword Confirm: " + change.NewPassword2);
Console.WriteLine();
Console.WriteLine("Let's see if the compare attribute works...");
Console.WriteLine("----------------------------------------------");
Console.WriteLine();
try
{
Validator.ValidateObject(change, new ValidationContext(change, null, null));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
throw ex;
}
Console.WriteLine("Validation doesn't work because you see this line.");
Console.ReadLine();
}
}
添加IValidatableObject
也不起作用。
我確實發現了Compare屬性中的另一個bug,該屬性目前還沒有與NuGet包一起發佈。 https://aspnetwebstack.codeplex.com/workitem/1401 –