2014-01-24 66 views
7

我有以下的HTML輔助方法:與通用paramerter轉換靜態方法泛型類

public static MvcHtmlString CustomEditorFor<TModel, TProperty>(this HtmlHelper<TModel> helper, 
     Expression<Func<TModel, TProperty>> expression, 
     EditorOptions options, 
     object htmlAttributes) 
{ 
} 

我有必要把它移到到一個輔助庫,以這種方式構成:

public class HtmlHelperExenion 
{ 
    public static Custom(this HtmlHelper helper) 
    { 
     return new HelperFactory(helper); 
    } 
} 

public class HelperFactory 
{ 
    internal HtmlHelper HtmlHelper { get; set; } 
    public HelperFactory(HtmlHelper htmlHelper) 
    { 
     this.HtmlHelper = htmlHelper; 
    } 

    public virtual EditorBuilder CustomEditorFor(parameters from static MvcHtmlString static method above go here) 
    { 
     return new EditorBuilder(parameters go here); 
    } 
} 

我無法弄清楚如何構建我的HelperFactory類和EditorBuilder類構造函數來正確處理泛型。

這是我嘗試過,並沒有奏效:

public static HelperFactory<TModel, TProperty> Custom<TModel, TProperty>(this HtmlHelper<TModel> helper) 
{ 
    return new HelperFactory<TModel, TProperty>(helper); 
} 

public class HelperFactory<TModel, TProperty> : HelperFactory 
{ 
    public HtmlHelper<TModel> HtmlHelper { get; set; } 

    public HelperFactory(HtmlHelper<TModel> htmlHelper) 
     : base((HtmlHelper)htmlHelper) 
    { 
     this.HtmlHelper = htmlHelper; 
    } 

    public virtual EditorBuilder<TModel, TProperty> CustomEditorFor(Expression<Func<TModel, TProperty>> expression, 
EditorOptions options, 
object htmlAttributes) 
    { 
     return new EditorBuilder<TModel, TProperty>(this.HtmlHelper, 
        expression, 
        options, 
        htmlAttributes); 
    } 
} 

public class EditorBuilder<TModel, TProperty> 
{ 
    public EditorBuilder(HtmlHelper<TModel> helper, 
     Expression<Func<TModel, TProperty>> expression, 
     EditorOptions options, 
     object htmlAttributes) 
    { 

    } 

} 

的最終目標是能夠以這種方式使用它: @ Html.Custom()CustomEditorFor(型號=> model.Property)

任何援助將不勝感激。

回答

1

你並不遙遠,只是改變你的HelperFactory採取TModel這樣你就可以把它綁通用HtmlHelper,並CustomEditorFor通用的,因此它可以接受任何TProperty

public class HelperFactory<TModel> 
{ 
    public HelperFactory(HtmlHelper<TModel> htmlHelper) 
    { 
     this.HtmlHelper = htmlHelper; 
    } 

    public HtmlHelper<TModel> HtmlHelper { get; private set; } 

    public virtual EditorBuilder<TModel, TProperty> CustomEditorFor<TProperty>(Expression<Func<TModel, TProperty>> expression, EditorOptions options, object htmlAttributes) 
    { 
     return new EditorBuilder<TModel, TProperty>(this.HtmlHelper, 
        expression, 
        options, 
        htmlAttributes); 
    } 
} 

然後,所有你需要做的被更新擴展方法

public static class HtmlHelperExt 
{ 
    public static HelperFactory<TModel> Custom<TModel>(this HtmlHelper<TModel> helper) 
    { 
     return new HelperFactory<TModel>(helper); 
    } 
} 

所以對於像

public class MyModel 
{ 
    public int Id { get; set; } 
    ... 
} 
0的模型

使用看起來像

@model MyModel 

@Html.Custom().CustomEditorFor(x => x.Id, EditorOptions.Option1, null)