I want to override Html.TextBoxFor () with my own helper, which has exactly the same signature (but, of course, a different namespace) - is this possible, and if so, how?
The reason for this is that I have more than 100 views in an existing application, and I want to change the behavior of TextBoxFor so that it displays the attribute maxLength = n if the property has the annotation [StringLength (n)].
The code for automatically output maxlength = n is in this question: the maxlength attribute of a text field from DataAnnotations StringLength in Asp.Net MVC . But my question is not a duplicate - I'm trying to create a more general solution: where DataAnnotaion automatically flows into html, without the need for additional code to be used by the person who writes the presentation.
In the question mentioned, you need to change each Html.TexBoxFor to Html.CustomTextBoxFor. I need to do this so that the existing TextBoxFor () does not need to be changed - therefore, creating an assistant with the same signature: change the behavior of the helper method and all existing instances will work without any changes (100+ views, at least 500 TextBoxFor () s - do not want to manually edit this).
I tried this code: (And I need to repeat it for each TextBoxFor overload, but as soon as the problem with the root is solved, it will be trivial)
namespace My.Helpers { public static class CustomTextBoxHelper { public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, bool includeLengthIfAnnotated) {
But I get a compiler error in the view on Html.TextBoxFor (): "The call is ambiguous between the following methods or properties" (of course). Is there any way to do this?
Is there an alternative approach that would allow me to change the behavior of Html.TextBoxFor, so now I donβt need to change existing views?
c # asp.net-mvc html-helper data-annotations
JK.
source share