简体   繁体   中英

Asp.Net MVC Call HtmlHelper with a variable

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM