开发者

EditorFor and StringLength DataAnnotations

开发者 https://www.devze.com 2023-03-28 15:13 出处:网络
I have the following property on my Model [Display(Name = \"MyProperty\"开发者_如何转开发)] [StringLength(10)]

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号