2009-11-05 50 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