DisplayFormat
is only used by MVC in any of the t21 razor extension methods. (e.g. DisplayFor
). Unfortunately, to do what you want, you will have to write the code "manually" ... here is an example to get you started. It mainly reproduces the TextBoxFor code, but makes some assumptions, which are most likely bad for production. Check out the purpose of the displayText
below, where we really care about the DisplayFormatString
that you set in your DisplayFormat
.
To call it in your view @Html.TextEditorFor(m => m.Value)
public static class CustomEditorFor { public static IHtmlString TextEditorFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) { return TextEditorFor(helper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } public static IHtmlString TextEditorFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); object value = metadata.Model; string displayText = string.Format(metadata.DisplayFormatString, value); string fullName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression)); TagBuilder tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("type", "text"); tagBuilder.MergeAttribute("name", fullName, true); tagBuilder.MergeAttribute("value", displayText); tagBuilder.GenerateId(fullName); ModelState modelState; if (helper.ViewData.ModelState.TryGetValue(fullName, out modelState)) { if (modelState.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } } tagBuilder.MergeAttributes(helper.GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata)); return new HtmlString(tagBuilder.ToString(TagRenderMode.SelfClosing)); } }
source share