2009-11-05 53 views
4

我想知道是否有人试图在MVC2中为LabelExtensions.LabelFor HtmlHelper编写扩展帮助器?这对我来说很有用,因为我的应用程序要求我总是将标签贴在带有class属性的<td>标签中。而不是让这些代码在我以为我可以写一个小扩展方法查看重复:ASP.NET MVC 2 Preview 2 - 扩展LabelExtensions.LabelFor

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

但是我上LabelFor行错误:

类型参数的方法“的System.Web。 Mvc.Html.LabelExtensions.LabelFor(System.Web.Mvc.HtmlHelper,System.Linq.Expressions.Expression>)'不能从使用情况中推断出来。尝试明确指定类型参数。

任何人都可以给我一个这个骨头?

+0

Bueller? Bueller? – plancake

回答

3

这可能为时已晚,以帮助你,但你需要在你的方法签名使用的HtmlHelper的通用版本,像这样:

public static MvcHtmlString RenderLabelFor<TModel, TValue> (
    this HtmlHelper<TModel> html, 
    Expression<Func<TModel, TValue>> value, 
    object htmlAttributes 
) 
{ 
    ... 
} 
+0

@Plancake:谢谢,这个问题和答案一起帮助我解决了这个难题。 –

0

尝试

public static MvcHtmlString RenderLabelFor<TModel, TValue> (HtmlHelper html, <Func<TModel, Value>> value, object htmlAttributes) where TModel : class 
+0

不,对不起。仍然抛出错误 – plancake

+0

还试图增加一个额外的where子句: 其中TValue:类 没有运气! – plancake