EditorFor 和 StringLength DataAnnotations
我的模型上有以下属性
[Display(Name = "MyProperty")]
[StringLength(10)]
public string MyProperty
{
get;set;
}
和以下 EditorFor 模板
<%@ Page Language="C#" MasterPageFile="Template.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Data" runat="server">
<%= Html.TextBox("", Model)%>
</asp:Content>
我遇到的问题是 StringLength 属性(可以理解)没有设置为限制文本框大小。我的答案是我应该如何获取要在模板中设置的属性?
谢谢
I have the following property on my Model
[Display(Name = "MyProperty")]
[StringLength(10)]
public string MyProperty
{
get;set;
}
and the following EditorFor template
<%@ Page Language="C#" MasterPageFile="Template.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="Data" runat="server">
<%= Html.TextBox("", Model)%>
</asp:Content>
The problem I have is that the StringLength property (understandably), isn't being set to limit the textbox size. My answer is how should I be obtaining the attributes to set in my template?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是 ASP.NET MVC 3 或更高版本,则接受的答案不起作用。您需要更改用于获取值的键:
The accepted answer doesn't work if you are using ASP.NET MVC 3 or later. You need to change the keys used to get the value:
元数据属性和验证属性之间存在差异。
StringLengthAttribute
是一个验证属性,因此您无法从ModelMetadata
获取它。幸运的是,Wayne Brantley 已经完成了艰苦的工作 。以下是他获取验证规则的方式:
注意:如果您使用的是 ASP.NET MVC 3 或更高版本,则需要将
stringLength
更改为length 和
maximumLength
到max
。There is a difference between metadata attributes and validation attributes.
StringLengthAttribute
is a validation attribute, so you can't get it fromModelMetadata
.Luckily, Wayne Brantley has done the hard work. Here is how he gets the validation rules:
Note: if you are using ASP.NET MVC 3 or later, you will need to change
stringLength
tolength
andmaximumLength
tomax
.