views:

32

answers:

2

Hi All

Would anyone be able to advise if it’s possible to re-use an existing HtmlHelper within a new custom Html helper. For example:

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

The above is a simple example, but essentially I would like to group some logic & formatting for a group of html helpers rendering a view. This view would be used in a couple of places, hence I’d like to re-use the code. However in all my current attempts I have been unable to access methods like ‘CheckBox’ or ‘BeginForm’. Perhaps I'm using the HtmlHelper object incorrectly?

Does anyone know if this can be done?

Thanks, Matt

+3  A: 

In your example I think you'd need to do:

public static class GridHelper 
{ 
    public static string RenderGrid(this HtmlHelper helper, Object routeParams) 
    {           
        return helper.BeginForm(routeParams); 
    } 
} 
Paul Hadfield
+1  A: 

Did you add the following using ?

using System.Web.Mvc.Html;

You can also use generic helpers :

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

But you don't need to call the static class, you can directly use 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 );
    }
}
mathieu
I was missing the using. Thanks very much for your help.
Matt