I'm looking to augment the "Html.TextBoxFor" extension to meet some specific client needs.
As a sanity check, I started simple, and just created a Test extension method which would simply delegate to the existing functionality:
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 up with annotations, ie:
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 expected mark-up, ie:
@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 this:
@Html.Test(e=>e.MaxLength10)
<input id="MaxLength10" name="MaxLength10" type="text" value="">
What happened to all the nice data annotation tags?
I have a similar extension method that creates a watermark textbox that works correctly. Give it a shot to see if it fixes your issue. Also take a look at the ModelMetadata instance to see if it is getting 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With