Asp.net mvc 如何使用ASP.NET MVC 2验证两个属性
我刚刚开始使用ASP.NET MVC 2,并尝试验证 假设我有两个属性:Asp.net mvc 如何使用ASP.NET MVC 2验证两个属性,asp.net-mvc,validation,asp.net-mvc-2,c#-3.0,Asp.net Mvc,Validation,Asp.net Mvc 2,C# 3.0,我刚刚开始使用ASP.NET MVC 2,并尝试验证 假设我有两个属性: 密码1 密码2 我想要求他们都被填写,并且要求在模型生效之前两者都是相同的 我有一个简单的类叫做“NewUser” 我将如何实现这一点?我已经读过ValidationAttribute,并且理解这一点。但我不知道如何使用它来实现一个验证,将两个或多个属性与eathother进行比较 提前谢谢 具有以下解决方案的问题: 当将此应用于应用程序,并且ModelBinder运行模型验证时,出现问题: 如果属性级Validati
- 密码1
- 密码2
如果您对此问题有解决方案,请分享您的经验。非常感谢 Visual Studio的默认ASP.NET MVC 2模板包含所需的确切验证属性。从
AccountModels.cs
文件粘贴:
[AttributeUsage(AttributeTargets.Class,
AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute {
private const string _defaultErrorMessage =
"'{0}' and '{1}' do not match.";
private readonly object _typeId = new object();
public PropertiesMustMatchAttribute(string originalProperty,
string confirmProperty)
: base(_defaultErrorMessage) {
OriginalProperty = originalProperty;
ConfirmProperty = confirmProperty;
}
public string ConfirmProperty { get; private set; }
public string OriginalProperty { get; private set; }
public override object TypeId {
get {
return _typeId;
}
}
public override string FormatErrorMessage(string name) {
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, ConfirmProperty);
}
public override bool IsValid(object value) {
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(value);
object originalValue = properties.Find(OriginalProperty,
true /* ignoreCase */).GetValue(value);
object confirmValue = properties.Find(ConfirmProperty,
true /* ignoreCase */).GetValue(value);
return Object.Equals(originalValue, confirmValue);
}
}
如何使用:
[PropertiesMustMatch("Password", "ConfirmPassword",
ErrorMessage = "The password and confirmation password do not match.")]
class NewUser {
[Required]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Confirm password")]
public string ConfirmPassword { get; set; }
}
我能看到的唯一问题是,当模型的两个属性(本例中的类)不相等时,它不会像[Required]和m.Password1)%>@CodeMonkey那样将特定属性表示为包含错误,我明白了。尽管我不确定是否有一个优雅的解决方案可以让它以另一种方式工作,即使用模型绑定。毕竟,这在技术上是类级验证。如果必须将错误添加到属性中,那么在绑定后检查控制器中的两个值可能是最快的解决方案(虽然不是最优雅的)。在MVC 2版本中,Html.ValidationSummary帮助器方法现在可以仅显示模型级错误