Reputation:
I use HtmlHelper (in Asp.Net MVC 4.5) to create multiple validated fields per class property. Right now, I need to call them all in succession.
@Html.LabelFor(m => m.SomeField)
@Html.EditorFor(m => m.SomeField)
@Html.ValidationMessageFor(m => m.SomeField)
So instead, I would prefer to just pass the "m => m.SomeField" to a ViewHelper and have it be something like this.
@helper FieldHelper([???] ValueINeed)
{
@Html.LabelFor(ValueINeed)
@Html.EditorFor(ValueINeed)
@Html.ValidationMessageFor(ValueINeed)
}
// And then call the helper with...
ViewHelper.FieldHelper(m => m.SomeField)
My question is: Is this possible? What kind of type is the variable? Microsoft documentation says that it's "Expression<Func<TModel, TValue>>" but I haven't been able to construct such an object with the value. Thanks everyone in advance.
Upvotes: 1
Views: 591
Reputation: 11673
I don't think you can do this with helpers, I'm pretty sure your going to have to create an extension method instead:
public static MvcHtmlString FieldHelper<TModel, TItem>(this HtmlHelper<TModel> html, Expression<Func<TModel, TItem>> expr)
{
var output = html.LabelFor(expr);
output += html.EditorFor(expr);
output += html.ValidationMessageFor(expr);
return MvcHtmlString.Create(output);
}
Then in your view called with:
@Html.FieldHelper(x => x.SomeField)
Upvotes: 2