How can I use an @HtmlHelper inside a custom @Html

2019-07-27 02:54发布

问题:

I am trying to create a custom Html helper with ASP.NET MVC. I have the following code:

@helper DefaultRenderer(Models.Control control)
{
  <div class="form-group">
    <label class="control-label" for="@control.Name">@control.Label</label>
    @Html.TextBoxFor(m => control.Value, new { @class = "form-control" })
  </div>
}

Apparently @Html.TextBoxFor cannot be found inside a Helper .cshtml class. I can use it in a partial view which is also a .cshtml class.

I can use @HtmlTextBox but then I will lose the strong model binding...

Why is this happening and is there a way to get it to work?

回答1:

No, this is not possible. You could not write a normal HTML helper with @Html.TextBoxFor because that your view is strongly typed. So you need something like:

public class HelperExtentions{

     public static MvcHtmlString DefaultRenderer<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, Control control , object htmlAttributes)
        {
            var sb = new StringBuilder();
            var dtp = htmlHelper.TextBoxFor(expression, htmlAttributes).ToHtmlString();
            sb.AppendFormat("<div class='form-group'><label class='control-label' for='{1}'>{2}</label>{0}</div>", dtp,control.Name,control.Label);
            return MvcHtmlString.Create(sb.ToString());
        }
}

Then you can use :

@html.DefaultRenderer(m => m.Control.Value, Models.Control,new { @class = "form-control" }