如何将默认MVC 3项目中的成员资格提供程序(取自web.config)中的值传递给AccountModels中的验证属性?
Membership.MinRequiredPasswordLength
返回从web.config获取的值,Register.cshtml视图使用它:
<p>
Passwords are required to be a minimum of @Membership.MinRequiredPasswordLength
characters in length.
</p>
但似乎AccountModels文件中的ViewModel具有硬编码的值:
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
那么如何将web.config中的值传递给MinimumLength参数?
答案 0 :(得分:3)
您将无法像您希望的那样动态指定属性属性。这就是模板硬编码的原因。仍然使用数据注释的解决方法是让您的视图模型实现IValidatableObject,并让它根据Membership.MinRequiredPasswordLength检查密码。另一种选择是创建一个继承自ValidationAttribute的属性,并检查Membership.MinRequiredPasswordLength。
David Hayden有post covering both of these options.
对于客户端,您需要在模型或自定义属性上实现IClientValidatable。这是另一个显示示例的answer。您还需要添加客户端验证功能,并且可以在Razor视图中使用@ Membership.MinRequiredPasswordLength来获取值。