根据Model验证ASP.NET MVC2 FormCollection

时间:2011-04-11 00:58:42

标签: c# asp.net-mvc-2 validation model-binding

假设我有一个用户类设置,验证如下:

[MetadataType(typeof(ssUserMetaData))]
public partial class ssUser
{

}

class ssUserMetaData
{
    [Required(ErrorMessage = "Name is a required field.")]
    [StringLength(100, ErrorMessage = "Name must be 100 characters or less.")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Username is a required field.")]
    [StringLength(50, ErrorMessage = "Username must be 50 characters or less.")]
    public string Username { get; set; }

    [Required(ErrorMessage = "Email address is a required field.")]
    [Email(ErrorMessage = "Email address must be a valid format.")]
    [StringLength(100, ErrorMessage = "Email address must be 100 characters or less.")]
    [DisplayName("Email address")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Password is a required field.")]
    [StringLength(1000, MinimumLength = 6, ErrorMessage = "Passwords must be at least 6 characters long.")]
    [DisplayName("Password")]
    public string PasswordHash { get; set; }
}

现在,我有一个更新方法,只允许用户更新一些字段,如姓名和电子邮件。我不想重新提交此表单的所有数据以传递模型绑定,但我想使用此处配置的验证规则来检查表单集合中的特定值。

像这个虚构的代码......

bool result = ModelState.ValidateField("Email", formCollection["Email"]);

有没有办法做这样的事情,所以我可以避免重复我的验证规则?谢谢!

1 个答案:

答案 0 :(得分:2)

小表单使用NameAndEmail类和大表单使用SsUserMetaData怎么样?

class NameAndEmail
{
    [Required(ErrorMessage = "Name is a required field.")]
    [StringLength(100, ErrorMessage = "Name must be 100 characters or less.")]
    public string Name { get; set; }


    [Required(ErrorMessage = "Email address is a required field.")]
    [Email(ErrorMessage = "Email address must be a valid format.")]
    [StringLength(100, ErrorMessage = "Email address must be 100 characters or less.")]
    [DisplayName("Email address")]
    public string Email { get; set; }
}
class SsUserMetaData : NameAndEmail
{
    [Required(ErrorMessage = "Username is a required field.")]
    [StringLength(50, ErrorMessage = "Username must be 50 characters or less.")]
    public string Username { get; set; }


    [Required(ErrorMessage = "Password is a required field.")]
    [StringLength(1000, MinimumLength = 6, ErrorMessage = "Passwords must be at least 6 characters long.")]
    [DisplayName("Password")]
    public string PasswordHash { get; set; }
}