如何在自定义@HtmlHelper中使用@HtmlHelper? [英] How can I use an @HtmlHelper inside a custom @HtmlHelper?

查看:88
本文介绍了如何在自定义@HtmlHelper中使用@HtmlHelper?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ASP.NET MVC创建自定义HTML帮助器.我有以下代码:

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

显然,在Helper .cshtml类中找不到@ Html.TextBoxFor.我可以在也是.cshtml类的局部视图中使用它.

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.

我可以使用@HtmlTextBox,但随后我将失去强大的模型绑定...

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?

推荐答案

否,这是不可能的.您无法使用 @ Html.TextBoxFor 编写普通的HTML helper ,因为该视图是强类型的.所以你需要像这样的东西:

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());
        }
}

然后您可以使用:

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

这篇关于如何在自定义@HtmlHelper中使用@HtmlHelper?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆