Nik*_* S. 6 c# asp.net localization asp.net-membership asp.net-mvc-3
通常为ASP.NET MVC 3 Membership生成的代码,特别是NewPassword类的属性ChangePasswordModel看起来大致如下:
[Required]
[StringLength(100, MinimumLength=6)]
[DataType(DataType.Password)]
[Display("Name = CurrentPassword")]
public string NewPassword { get; set; }
Run Code Online (Sandbox Code Playgroud)
为了用我正在使用的外部参数填充一些信息RecourceType:
(在这种情况下,我正在更改OldPassword并Display使用资源中的一些其他数据填充属性
[Required]
[DataType(DataType.Password)]
[Display(ResourceType = typeof(Account), Name = "ChangePasswordCurrent")]
public string OldPassword { get; set; }
Run Code Online (Sandbox Code Playgroud)
回到NewPassword.我怎么能代替MinimumLenght用Membership.MinRequiredPasswordLength?:我的尝试:
[Required]
[StringLength(100, MinimumLength=Membership.MinRequiredPasswordLength)]
[DataType(DataType.Password)]
[Display(ResourceType=typeof(Account), Name= "ChangePasswordNew")]
public string NewPassword { get; set; }
Run Code Online (Sandbox Code Playgroud)
这会产生错误:
属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式(http://msdn.microsoft.com/de-de/library/09ze6t76%28v=vs.90%29.aspx)
验证属性必须是编译常量(如错误消息状态)。您可以创建自己的 ValidationAttribute 来为您处理这个最小长度。
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidatePasswordLengthAttribute : ValidationAttribute
{
private const string DefaultErrorMessage = "'{0}' must be at least {1} characters long.";
private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength;
public ValidatePasswordLengthAttribute() : base(DefaultErrorMessage)
{
}
public override string FormatErrorMessage(string name)
{
return string.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name, _minCharacters);
}
public override bool IsValid(object value)
{
var valueAsString = value.ToString();
return (valueAsString != null) && (valueAsString.Length >= _minCharacters);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你的视图模型可能看起来像这样(你甚至可以变得更奇特,并在 ValidatePasswordLength 属性中添加 DataAnnotations 的最大长度部分以删除该行)
[Required]
[StringLength(100)]
[DataType(DataType.Password)]
[Display(ResourceType=typeof(Account), Name= "ChangePasswordNew")]
[ValidatePasswordLength]
public string NewPassword { get; set; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6000 次 |
| 最近记录: |