Using DisplayFor inside a display template
- by Oenotria
I've created a htmlhelper extension to reduce the amount of repetitive markup when creating forms:
public static MvcHtmlString RenderField<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
{
return htmlHelper.DisplayFor(expression, "formfield");
}
The idea being that inside my views I can just write @Html.RenderField(x=>x.MyFieldName) and it will print the label and the field's content with the appropriate div tags in place already.
Inside the displaytemplates folder I have created formfield.cshtml containing the following:
<div class="display-group">
<div class="display-label">
@Html.LabelFor(x => x)
</div>
<div class="display-field">
@Html.DisplayFor(x => x)
</div>
</div>
Unfortunately it doesn't appear that it is possible to nest DisplayFor inside a display template (it doesn't render anything). I don't want to just using @Model because then I won't get checkboxes for boolean values, calendar controls for dates etc.
Is there a good way around this?