【问题标题】:Nested Html Helpers嵌套的 Html 助手
【发布时间】:2014-11-20 23:31:11
【问题描述】:

我有以下简单的剃须刀代码:

<div class="form-group">
    @Html.LabelFor(model => model.BusinessName, new { @class = "col-sm-3 control-label" })
      <div class="col-sm-6">
          @Html.TextBoxFor(model => model.BusinessName, new { @class = "form-control" })
          @Html.ValidationMessageFor(model => model.BusinessName)
      </div>
</div>

我希望能够将这一切包装在自定义 html 帮助程序中,但是,在阅读有关创建自己的帮助程序时,我看不到如何将现有的“TextBoxFor”和“ValidationMessageFor”帮助程序传递给自定义我将要创建的 html 辅助构造函数。有没有办法做到这一点,或者我会更好地查看我想要嵌套的助手的输出并在我的自定义助手中手动创建必要的标签?

【问题讨论】:

  • 为什么要使用自定义助手而不是使用显示模板来实现相同的结果?

标签: c# asp.net-mvc razor


【解决方案1】:

您必须传入一个表达式,该表达式返回您在帮助器中使用的模型的属性。从那里,您可以使用 TagBuilder 对象来构造您想要的 HTML。

public static class HtmlHelperExtensions
{
    public static MvcHtmlString FormGroup<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
    {
        var labelFor = html.LabelFor(expression);
        var textBoxFor = html.TextBoxFor(expression);
        var validationMessageFor = html.ValidationMessageFor(expression);

        var innerDivWrapper = new TagBuilder("div");
        innerDivWrapper.AddCssClass("col-sm-6");
        innerDivWrapper.InnerHtml = textBoxFor.ToHtmlString() + validationMessageFor.ToHtmlString();

        var wrapperTagBuilder = new TagBuilder("div");
        wrapperTagBuilder.AddCssClass("form-group");
        wrapperTagBuilder.InnerHtml = labelFor.ToHtmlString() + innerDivWrapper;

        return new MvcHtmlString(wrapperTagBuilder.ToString());
    }
}

您的扩展方法必须采用两个类型参数:TModel 知道您的模型类型是什么,TValue 知道表达式返回的类型。

该方法在 Razor 模板中的使用方式如下:

@Html.FormGroup(x => x.City)

正如 Venkat 在他的评论中指出的那样,这可能会通过显示模板更好地实现,但这将完成问题中描述的工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多