【问题标题】:Is it possible to use the HtmlHelper object in custom helper?是否可以在自定义助手中使用 HtmlHelper 对象?
【发布时间】:2011-04-09 02:29:13
【问题描述】:

谁能建议是否可以在新的自定义 Html 帮助器中重用现有的 HtmlHelper。例如:

public static class GridHelper
{
    public static string RenderGrid(this HtmlHelper helper, Object routeParams)
    {          
        return HtmlHelper.BeginForm(routeParams);
    }
}

上面是一个简单的例子,但本质上我想为一组渲染视图的 html 助手分组一些逻辑和格式。这个视图将在几个地方使用,因此我想重用代码。但是,在我目前的所有尝试中,我都无法访问诸如“CheckBox”或“BeginForm”之类的方法。也许我错误地使用了 HtmlHelper 对象?

有谁知道这是否可以做到?

谢谢,马特

【问题讨论】:

  • 还没有足够的代表来编辑问题,您的示例中的轻微拼写错误让我有一段时间。在您的返回语句中,您错误地在“HtmlHelper”的末尾添加了一个“t”,我猜。

标签: c# asp.net-mvc html-helper


【解决方案1】:

在您的示例中,我认为您需要这样做:

public static class GridHelper 
{ 
    public static string RenderGrid(this HtmlHelper helper, Object routeParams) 
    {           
        return helper.BeginForm(routeParams); 
    } 
} 

【讨论】:

    【解决方案2】:

    您是否使用添加了以下内容?

    using System.Web.Mvc.Html;
    

    您也可以使用通用助手:

    public static string RenderGrid<TModel, TProperty>(this HtmlHelper helper<TModel>, Expression<Func<TModel, TProperty>> displayExpression, Object routeParams)
    

    但是不需要调用静态类,直接使用helper即可:

    public static class GridHelper
    {
        public static string RenderGrid(this HtmlHelper helper, Object routeParams)
        {          
            return helper.CheckBox("foo");
        }
    }
    
    public static string RenderGrid<TModel, TProperty>(this HtmlHelper helper<TModel>, Expression<Func<TModel, TProperty>> expr, Object routeParams)
    {
        public static string RenderGrid(this HtmlHelper helper, Object routeParams)
        {          
            return helper.CheckBoxFor( expr );
        }
    }
    

    【讨论】:

    • 我错过了使用。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 2012-04-24
    • 2011-12-15
    相关资源
    最近更新 更多