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

会有一股神秘感。 提交于 2020-01-15 09:54:26

问题


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" }


来源:https://stackoverflow.com/questions/43858102/how-can-i-use-an-htmlhelper-inside-a-custom-htmlhelper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!