HTMLHelper MVC5 extension does not return expected content

I want to increase the extension "Html.TextBoxFor" to meet the specific needs of the client.

As a health check, I started simply and simply creating a test extension method that would simply delegate to existing functions:

public static class HtmlExtensions { public static MvcHtmlString Test<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { return htmlHelper.TextBoxFor(expression); } } 

Everything seemed to work until I tried this against a model marked with annotations, i.e.

 public class TestRoot { [Display(Name = "Max Length 10")] [Required] [StringLength(10)] public string MaxLength10 { get; set; } } 

When I call the built-in TextBoxFor function, I get all the expected markups, that is:

@ Html.TextBoxFor (e => e.MaxLength10)

 <input data-val="true" data-val-length="The field Max Length 10 must be a string with a maximum length of 10." data-val-length-max="10" data-val-required="The Max Length 10 field is required." id="MaxLength10" name="MaxLength10" type="text" value=""> 

When I called my extension, I expected the same content, but instead I get the following:

@ Html.Test (e => e.MaxLength10)

 <input id="MaxLength10" name="MaxLength10" type="text" value=""> 

What happened to all the great annotation tags?

+6
source share
1 answer

I have a similar extension method that creates the correct watermark text box. Let him know if he fixes your problem. Also take a look at the ModelMetadata instance to make sure it is created correctly.

 public static MvcHtmlString WatermarkTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData); string watermark = !String.IsNullOrEmpty(metadata.Watermark) ? metadata.Watermark : metadata.DisplayName; var attributes = htmlHelper.MergeAttributes(htmlAttributes, new { placeholder = watermark }); return htmlHelper.TextBoxFor<TModel, TProperty>(expression, attributes); } 
+1
source

All Articles