'Compare' 是 'System.ComponentModel.DataAnnotations.CompareAttribute' 和 'System.Web.Mvc.CompareAttribute' 之间的模糊引用

'Compare' is an ambiguous reference between 'System.ComponentModel.DataAnnotations.CompareAttribute' and 'System.Web.Mvc.CompareAttribute'

我的 AccountController 中有这个错误。

The type or namespace name 'SelectListItem' could not be found ( are you missing a using directive or an assembly reference?

明显的解决方法是添加 using System.Web.Mvc; 但是当我这样做时我得到 4 个新错误

两条不同的线:

The type or namespace name 'ErrorMessage' could not be found (are you missing a using directive or an assembly reference?)

在另外 2 条不同的线路上:

'Compare' is an ambiguous reference between 'System.ComponentModel.DataAnnotations.CompareAttribute' and 'System.Web.Mvc.CompareAttribute'

为什么会发生这种情况,我该如何解决?

public class RegisterViewModel
    {
[DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
       public IEnumerable<SelectListItem> DepotList { get; set; }


}

重置密码视图模型

public class ResetPasswordViewModel
{

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]

}

是的。这两个名称空间都具有具有相同功能的属性。

根据msdn documentationSystem.Web.Mvc.CompareAttribute已过时,建议使用System.ComponentModel.DataAnnotations.CompareAttribute

所以要么使用包括命名空间的完全限定名称。

[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[System.ComponentModel.DataAnnotations.Compare("Password",
                    ErrorMessage = "The password and confirmation password do not match.")]
public string Name { get; set; }

或者如果您不想在所有地方都使用完全限定名称,您可以使用别名

using Compare = System.ComponentModel.DataAnnotations.CompareAttribute;
public class ResetPasswordViewModel
{
   [DataType(DataType.Password)]   
   [Compare("Password", ErrorMessage = "The password and confirm password do not match.")]
   public string Password { set;get;}
   //Other properties as needed
}