asp.net - ASP.NET MVC数据注释MaxLength验证不起作用

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

我在模型中使用asp.net mvc4,但是正在使用Maxlength属性,但不适用于字符串。
只有Stringlength可以解决任何人的问题吗?如果有问题怎么解决?它不适用于验证我的 Realm
这是我的代码

(不工作)

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

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

最佳答案

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

按照Microsoft官方网站Entity Framework中的[MaxLength]属性
因为在这种情况下,Entity Framework知道数据库中列的最大长度是多少(例如 varchar(80))

Specifies the maximum length of array or string data allowed in a property.



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

正如您在其中一个评论中所言,您说您不使用Entity Framework来回复 @jackncoke ,所以[MaxLength(80)]无法使用

但是在第二种情况下,[StringLength(80)]有效,因为它对 Entity Framework 没有任何依赖性。

如果您使用或不使用Entity Framework,那么[StringLength(80)]在两种情况下都可以使用

Specifies the minimum and maximum length of characters that are allowed in a data field.



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

关于asp.net - ASP.NET MVC数据注释MaxLength验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14629095/

相关文章:

c# - 身份在 Asp .Net MVC 5 中如何工作

html - 将标签和水平复选框列表彼此相邻放置

asp.net - 为什么 Html.DisplayFor 和 .ToString ("C2") 不尊重 CurrentUICulture?

html - 如何根据其内部文本(英语/阿拉伯语)设置正确的元素 css 方向(ltr/rtl)?

c# - POST 到 C# 时 JSON 对象为空

unit-testing - 单元测试 MVC 身份验证 VS 2013

c# - 在 c# asp.net 中创建自定义警报框

c# - 使用数据集处理分页和 "lazy-loading"?

jquery - 使用 MVC 4 和 Ajax 上传文件

c# - 如何自定义 JSON 序列化?