Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I use the CustomModelMetaDataProvider to achieve this </p> <p>Step 1. Add New CustomModelMetadataProvider class</p> <pre><code>public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider { protected override ModelMetadata CreateMetadata( IEnumerable&lt;Attribute&gt; attributes, Type containerType, Func&lt;object&gt; modelAccessor, Type modelType, string propertyName) { ModelMetadata metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName); //Add MaximumLength to metadata.AdditionalValues collection var stringLengthAttribute = attributes.OfType&lt;StringLengthAttribute&gt;().FirstOrDefault(); if (stringLengthAttribute != null) metadata.AdditionalValues.Add("MaxLength", stringLengthAttribute.MaximumLength); return metadata; } } </code></pre> <p>Step 2. In Global.asax Register the CustomModelMetadataProvider </p> <pre><code>protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); ModelMetadataProviders.Current = new CustomModelMetadataProvider(); } </code></pre> <p>Step 3. In Views/Shared/EditorTemplates Add a partial view called String.ascx</p> <pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt; &lt;%if (!ViewData.ModelMetadata.AdditionalValues.ContainsKey("MaxLength")) { %&gt; &lt;%: Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line" }) %&gt; &lt;% } else { int maxLength = (int)ViewData.ModelMetadata.AdditionalValues["MaxLength"]; %&gt; &lt;%: Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line", MaxLength = maxLength })%&gt; &lt;% } %&gt; </code></pre> <p>Done... </p> <p><strong>Edit. The Step 3 can start to get ugly if you want to add more stuff to the textbox. If this is your case you can do the following:</strong></p> <pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt; &lt;% IDictionary&lt;string, object&gt; Attributes = new Dictionary&lt;string, object&gt;(); if (ViewData.ModelMetadata.AdditionalValues.ContainsKey("MaxLength")) { Attributes.Add("MaxLength", (int)ViewData.ModelMetadata.AdditionalValues["MaxLength"]); } if (ViewData.ContainsKey("style")) { Attributes.Add("style", (string)ViewData["style"]); } if (ViewData.ContainsKey("title")) { Attributes.Add("title", (string)ViewData["title"]); } %&gt; &lt;%: Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, Attributes)%&gt; </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