c# - “比较”是 'System.ComponentModel.DataAnnotations.CompareAttribute' 和 'System.Web.Mvc.CompareAttribute' 之间的模糊引用

标签 c# asp.net-mvc entity-framework asp.net-identity

我的 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?)

另外两条不同的线:

'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; }


}

重置密码 View 模型

public class ResetPasswordViewModel
{

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

}

最佳答案

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

根据 msdn documentation , System.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
}

关于c# - “比较”是 'System.ComponentModel.DataAnnotations.CompareAttribute' 和 'System.Web.Mvc.CompareAttribute' 之间的模糊引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36318044/

相关文章:

c# - 如何在 Controller 之外使用 EF DbContext?

c# - 为什么这个 oracle 批量插入不起作用?

c# - 查看将在 HttpResponseMessage/HttpRequestMessage (System.Net.Http, WebAPI) 中发送/接收的原始 header

c# - 使用准无服务器 Web 架构(AJAX 模板魔法)确保安全 "private site areas"

c# - EntityFramework.Extended Future 错误(JIT 编译器内部限制)

c# - Entity Framework 通用存储库,包括通过参数的属性

C# 程序想要选择数据 <= 23 :59:59 but ends up selecting data with 00:00:00 timestamp as well

c# - 如何在 Binding StringFormat 中使用变量文本?

c# - stringbuilder 追加带有变量的文本

c# - 系统.Data.SqlClient.SqlException : Invalid column name 'phone_types_phone_type_id'