Reputation: 1014
I am creating LOB business application using ASP.NET MVC. In my views I find this pattern repeated a lot:
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
It must be possible to write a helper to reduce it down to something like this:
@EditorForField(model => model.Name)
This will make the views simpler, and make it easier to change the form layout to table based layout (if required)
Any ideas how to make such a helper method?
Thanks!
Upvotes: 2
Views: 642
Reputation: 1014
I was able to make this work by this code:
public static class HelperExtensions
{
public static MvcHtmlString EditorForField<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression)
{
const string template = @"<div class=""editor-label"">{0}</div><div class=""editor-field"">{1}{2}</div>";
string markup = string.Format(template,
html.LabelFor(expression),
html.EditorFor(expression),
html.ValidationMessageFor(expression));
return new MvcHtmlString(markup);
}
}
In your View:
@Html.EditorForField(model => model.Name)
Upvotes: 2