Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditorFor and StringLength DataAnnotations

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

like image 227
user460667 Avatar asked Dec 03 '22 07:12

user460667


1 Answers

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"];
}
like image 112
salgiza Avatar answered Dec 14 '22 18:12

salgiza