Compare属性不使用比较属性的Display属性

时间:2013-08-23 22:48:29

标签: c# asp.net-mvc-4 properties attributes data-annotations

我有一个用于更改密码的ViewModel,它使用Compare DataAnnotation,如下所示:

[Display(Name = "New Password")]
public string New { get; set; }

[Compare("New")]
[Display(Name = "Confirm Password")]
public string ConfirmPassword { get; set; }

不幸的是,Compare属性未使用比较属性的Display属性。

错误消息显示为

'Confirm Password' and 'New' do not match.
您可以看到

使用比较属性的Display属性,但不使用比较属性。

我还会指定我不想使用ErrorMessage参数,因为那时我会对属性名称进行硬编码,而不是简单地从现有属性中获取它。我想尽可能保持这种解决方案的最佳实践。

如何使Compare属性使用比较属性的Display属性?

2 个答案:

答案 0 :(得分:2)

我认为这可能是Compare属性的一些问题,因为您可以在其属性列表中看到OtherDisplayName属性,并且它正确地使用它正在装饰的属性的显示名称(“确认密码”而不是“确认密码”)。

我找到的一个解决方法是简单地创建一个继承自CompareAttribute的新类,如下所示:

public class CompareWithDisplayName : CompareAttribute
{
    public CompareWithDisplayName(string otherProperty) : base(otherProperty)
    {
    }
}

然后在你的财产上使用它:

[Display(Name = "New Password")]
public string New { get; set; }


[Display(Name = "Confirm Password")]
[CompareWithDisplayName("New")]
public string ConfirmPassword { get; set; }

老实说,我不知道为什么会这样。可能是它与反射有关,或者它决定每个属性的显示属性的顺序。通过创建它的自定义版本,可能会更改排序?无论哪种方式,这对我来说都是诀窍:)

编辑2 抱歉,忘记添加客户端验证所需的额外部分,解释为here。您可以在 Global.asax.cs 文件中添加它:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CompareWithDisplayName), typeof(CompareAttributeAdapter))

或在自定义属性上实现IClientValidatable接口。这两个都显示在链接

答案 1 :(得分:2)

也许为时已晚,但是我在Asp.Net Core Razor Page Web App中遇到了同样的问题,最简单的解决方法是使用Password和ConfirmPassword属性创建一个新的InputModel类,然后将表单输入绑定到InputModel属性。

赞:

    [BindProperty]
    public InputModel UserPassword { get; set; }

    public class InputModel {
      [BindProperty]
      [Display(Name = "Contraseña")]
      [Required(ErrorMessage = "La contraseña es obligatoria.")]
      [RegularExpression("^[a-zA-ZñÑ0-9]+$",ErrorMessage = "Sólo se permiten letras y números.")]
      [StringLength(12,ErrorMessage = "La contraseña no debe tener más de 12 caracteres.")]
      [MaxLength(12,ErrorMessage = "La contraseña no debe tener más de 12 caracteres.")]
      [MinLength(2,ErrorMessage = "La contraseña no debe tener menos de 2 caracteres.")]
      public string Password { get; set; }

      [BindProperty]
      [Display(Name = "Confirmación de Contraseña")]
      [Required(ErrorMessage = "La contraseña es obligatoria.")]
      [Compare(nameof(Password),ErrorMessage = "La contraseña de confirmación no coincide.")]
      public string ConfirmPassword { get; set; }
    }
相关问题