views:

516

answers:

2

I'm wondering if anyone has attempted to write an extension helper to the LabelExtensions.LabelFor HtmlHelper in MVC2? This would be useful for me in that my app requires that I always wrap labels in a <td> tag with a class attribute. Rather than have that code repeated in the View I thought I could write a little extension method:

public static MvcHtmlString RenderLabelFor<TModel, TValue> (
    this HtmlHelper html,
    Expression<Func<TModel, TValue>> value,
    object htmlAttributes
) where TModel : class
{
    TagBuilder builder = new TagBuilder("td");
    builder.MergeAttributes(new RouteValueDictionary(attributes)); // to convert an object into an IDictionary
    builder.InnerHtml = LabelExtensions.LabelFor(html, value).ToString();
    return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}

However I get the error on the LabelFor line:

The type arguments for method 'System.Web.Mvc.Html.LabelExtensions.LabelFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Can anyone throw me a bone on this one?

A: 

try public static MvcHtmlString RenderLabelFor<TModel, TValue> ( this HtmlHelper html, Expression<Func<TModel, TValue>> value, object htmlAttributes) where TModel : class

Yann
No, sorry. Still throws the error
plancake
Also tried adding an extra where clause:where TValue : classwith no luck!
plancake
+1  A: 

This may be too late to help you, but you need to use the generic version of HtmlHelper in your method signature, like so:

public static MvcHtmlString RenderLabelFor<TModel, TValue> (
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> value,
    object htmlAttributes
)
{
    ...
}
Gabe Moothart
@Gabe, @Plancake: Thanks, the question along with the answer has just saved me a headache of trying to figure this one out.
Paul Hadfield