我有以下html帮助方法:
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(型号=&GT; model.Property)。
非常感谢任何协助。
答案 0 :(得分: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; }
...
}
用法看起来像
@model MyModel
@Html.Custom().CustomEditorFor(x => x.Id, EditorOptions.Option1, null)