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
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:
IEnumerable<ModelValidator> validators = ModelValidatorProviders.Providers
.GetValidators(ViewData.ModelMetadata, ViewContext);
ModelClientValidationRule rule = validators.SelectMany(v =>
v.GetClientValidationRules()
).FirstOrDefault(m => m.ValidationType == "length");
if (rule != null && rule.ValidationParameters.ContainsKey("max")) {
var maxLength = rule.ValidationParameters["max"];
}
There is a difference between metadata attributes and validation attributes. StringLengthAttribute
is a validation attribute, so you can't get it from ModelMetadata
.
Luckily, Wayne Brantley has done the hard work. Here is how he gets the validation rules:
IEnumerable<ModelValidator> validators = ModelValidatorProviders.Providers.GetValidators(ViewData.ModelMetadata, ViewContext);
ModelClientValidationRule rule = validators.SelectMany(v => v.GetClientValidationRules()).FirstOrDefault(m => m.ValidationType == "stringLength");
if (rule != null && rule.ValidationParameters.ContainsKey("maximumLength"))
{
var maxLength = rule.ValidationParameters["maximumLength"];
}
Note: if you are using ASP.NET MVC 3 or later, you will need to change stringLength
to length
and maximumLength
to max
.
精彩评论