【发布时间】:2010-11-06 18:47:45
【问题描述】:
我有一个自定义验证属性,用于检查两个属性是否具有相同的值(例如密码和重新输入密码):
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class EqualToPropertyAttribute : ValidationAttribute
{
public string CompareProperty { get; set; }
public EqualToPropertyAttribute(string compareProperty)
{
CompareProperty = compareProperty;
ErrorMessage = string.Format(Messages.EqualToError, compareProperty);
}
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
var property = properties.Find(CompareProperty, true);
var comparePropertyValue = property.GetValue(value).ToString();
return comparePropertyValue == value.ToString();
}
}
我有一个视图模型类,其中包含注册表单的所有字段,如下所示:
public class SignUpViewModel
{
[Required]
[StringLength(100)]
public string Username { get; set; }
[Required]
[Password]
public string Password { get; set; }
[Required]
[DisplayText("RetypePassword")]
[EqualToProperty("Password")]
public string RetypePassword { get; set; }
[Required]
[StringLength(50)]
[DisplayText("FirstName")]
public string FirstName { get; set; }
[Required]
[StringLength(100)]
[DisplayText("LastName")]
public string LastName { get; set; }
[Required]
[DisplayText("SecurityQuestion")]
public int SecurityQuestionID { get; set; }
public IEnumerable<SelectListItem> SecurityQuestions { get; set; }
[Required]
[StringLength(50)]
public string Answer { get; set; }
}
下面是我的控制器代码:
public virtual ActionResult Index()
{
var signUpViewModel = new SignUpViewModel();
signUpViewModel.SecurityQuestions = new SelectList(questionRepository.GetAll(),"SecurityQuestionID", "Question");
return View(signUpViewModel);
}
[HttpPost]
public virtual ActionResult Index(SignUpViewModel viewModel)
{
// Code to save values to database
}
当我输入表单值并点击提交时,尝试获取属性描述符的代码行 var property = properties.Find(CompareProperty, true); 返回 null。谁能帮我理解为什么会这样?
【问题讨论】:
-
Object value被传递到 IsValid 方法中的是什么?看起来无论该对象是什么,它都没有密码属性 -
附带说明,MVC 3 有一个 CompareAttribute 可以完全满足您的要求。 我正在使用 MVC 3 rc - 比较不起作用 - 找不到类型或命名空间...?
-
CompareAttribute 位于 System.Web.Mvc 中,而 RequiredAttribute、StringLengthAttribute、... 位于 System.ComponentModel.DataAnnotations 中。
标签: c# asp.net asp.net-mvc-2 data-annotations