Using DisplayFor inside a display template

Posted by Oenotria on Stack Overflow See other posts from Stack Overflow or by Oenotria
Published on 2011-06-23T13:20:44Z Indexed on 2011/06/23 16:22 UTC
Read the original article Hit count: 192

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?

© Stack Overflow or respective owner

Related posts about asp.net-mvc-2

Related posts about asp.net-mvc-3