【问题标题】:Asp.net mvc dataannotation MaxLength validation does not workAsp.net mvc dataannotation MaxLength 验证不起作用
【发布时间】:2013-01-15 17:59:52
【问题描述】:

我在我的模型中使用 asp.net mvc4 我正在使用 Maxlength 属性,但它不适用于字符串。 只有 Stringlength 工作有人有同样的问题吗?如果有问题如何解决?它不适用于验证我的领域 这是我的代码

(不工作)

[Required]
[MaxLength(80)]
[DisplayName("Contact Name:")]
public string ContactName { get; set; }

(工作)

[Required]
[StringLength(80)]
[DisplayName("Contact Name:")]
public string ContactName { get; set; }

【问题讨论】:

  • 我没有收到错误消息。请提供 ContactName 所在的班级。
  • 我没有说我收到错误。我只是说它不起作用。

标签: asp.net asp.net-mvc-4


【解决方案1】:

两个属性都在 System.ComponentModel.DataAnnotations 命名空间中

根据微软官网[MaxLength] Entity Framework 属性 因为实体框架知道在您的情况下数据库中列的最大长度是多少(例如 varchar(80)

指定属性中允许的数组或字符串数​​据的最大长度。

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.maxlengthattribute.aspx

正如你们中的一个评论所说,您没有使用实体框架来回复 @jackncoke 所以[MaxLength(80)] 将不起作用

但在第二种情况下,[StringLength(80)] 正在工作,因为它与实体框架没有任何依赖关系。

如果您使用或不使用实体框架,那么[StringLength(80)] 在这两种情况下都可以工作

指定数据字段中允许的最小和最大字符长度。

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.stringlengthattribute.aspx

【讨论】:

    【解决方案2】:

    [MaxLength(80)] 更改为 [StringLength(80)] 但看起来你打败了我!

    你不是唯一一个有这个问题的人

    MaxLength Attribute not generating client-side validation attributes

    【讨论】:

    • 是的,我知道它可以与 [StringLength(80)] 一起使用,但我的问题是为什么不与 [MaxLength(80)] 一起使用?即使根据微软的说法,它也是有效的,但你是第一个回答的人,所以为你 +1
    • 我只是在浏览旧项目,我从未使用过它总是使用 StringLength。所以我一直在互联网上寻找其他人是否有这种问题。我已经看到人们在搜索时使用它。
    • 你用的是什么版本的EF?
    • 我没有使用实体框架,我正在将静态数据传递给我的模型。它应该没有任何区别。我很好奇它是否只对我或其他人也不起作用..
    【解决方案3】:

    IN MVC4 MaxLength 工作正常,我必须检查一下

    public class RegisterModel
    {
        [Required]
        [Display(Name = "User name")]
        [MaxLength(5)]  //MaxLength worked properly.
        public string UserName { get; set; }
    
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
    
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-19
      • 2015-05-02
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      • 2014-03-25
      • 2013-11-28
      • 2014-08-02
      • 1970-01-01
      相关资源
      最近更新 更多