1

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.

4
  • 2
    So what do you get from adding this extra layer of abstraction? ViewHelper.FieldHelper has more characters so what are you gaining? Commented Jan 28, 2020 at 17:23
  • Makes the View code a little easier to skim through. Also, the helper does a little more not showcased here, mainly providing a layout for company branded UI. Commented Jan 28, 2020 at 17:26
  • @CodingYoshi I noticed I had forgotten the two other fields from my example, sorry for the confusion. Commented Jan 28, 2020 at 17:31
  • I would do it through an extension such as Html.LabelCustomFor and copy the signature of Html.LabelFor. Within this new method add your custom stuff. Commented Jan 28, 2020 at 17:32

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

3 Comments

I remember trying something similar before, but for some reason the "...does not contain a definition for LabelFor" (etc.) problem always comes up.
More than likely missing using statements: using System.Web.Mvc; using System.Web.Mvc.Html;
You were correct, I indeed had forgotten an import. Thank you very much, this suggestion worked!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.