DisplayFormat
仅由 MVC 在Display
剃刀的任何扩展方法中使用。(例如DisplayFor
)不幸的是,要执行您想要的操作,您必须编写一些“手动”代码……这里有一个示例可以帮助您进行操作。它基本上复制了 TextBoxFor 代码,但做出了一些很可能对生产不利的假设。请注意下面的分配displayText
,这就是我们真正关心DisplayFormatString
您在DisplayFormat
.
在你的视图中调用它@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));
}
}