Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want this to work with a metadata class you need to use the following code. I know its not pretty but it gets the job done and prevents you from having to write your maxlength properties in both the Entity class and the View:</p> <pre><code>public static MvcHtmlString TextBoxFor2&lt;TModel, TProperty&gt; ( this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression, object htmlAttributes = null ) { var member = expression.Body as MemberExpression; MetadataTypeAttribute metadataTypeAttr = member.Member.ReflectedType .GetCustomAttributes(typeof(MetadataTypeAttribute), false) .FirstOrDefault() as MetadataTypeAttribute; IDictionary&lt;string, object&gt; htmlAttr = null; if(metadataTypeAttr != null) { var stringLength = metadataTypeAttr.MetadataClassType .GetProperty(member.Member.Name) .GetCustomAttributes(typeof(StringLengthAttribute), false) .FirstOrDefault() as StringLengthAttribute; if (stringLength != null) { htmlAttr = new RouteValueDictionary(htmlAttributes); htmlAttr.Add("maxlength", stringLength.MaximumLength); } } return htmlHelper.TextBoxFor(expression, htmlAttr); } </code></pre> <hr> <p><em>Example class</em>:</p> <pre><code>[MetadataType(typeof(Person.Metadata))] public partial class Person { public sealed class Metadata { [DisplayName("First Name")] [StringLength(30, ErrorMessage = "Field [First Name] cannot exceed 30 characters")] [Required(ErrorMessage = "Field [First Name] is required")] public object FirstName { get; set; } /* ... */ } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload