感谢 Itminus 回答我。
但是在控制器构造函数上调用 IHtmlHelper 是不够的,您必须在使用 IHtmlHelper 之前将其上下文化。
我想分享我找到的另一个解决方案并解决我的问题,也许它对其他用户有用。
请参阅https://gist.github.com/Blackleones/eb0d02b9dd99164271af88e22143d72b#file-example-cs 以记住我的目标。
- 为了解决我的问题,我创建了一个名为 HtmlHelperAdapter 的类,其中包含一些我需要的实例。
public class MyHtmlHelperAdapter
{
public IHtmlHelper _html;
public NubessHtmlHelperAdapter(IHtmlHelper html)
{
_html = html;
}
public IHtmlHelper Html => _html;
public ViewContext ViewContext => _html.ViewContext;
public HttpContext HttpContext => _html.ViewContext.HttpContext;
public ViewDataDictionary ViewData => _html.ViewData;
public IServiceProvider provider => _html.ViewContext.HttpContext.RequestServices;
}
- 之后我为 IHtmlHelper 创建了一个扩展方法
public static class MyBuilderExtension
{
public static MyBuilder Nubess(this IHtmlHelper html)
{
return new MyBuilder(new MyHtmlHelperAdapter(html));
}
}
MyBuilder 在哪里
public class MyBuilder
{
private readonly MyHtmlHelperAdapter _htmlHelper;
public MyBuilder(MyHtmlHelperAdapter htmlHelper)
{
_htmlHelper = htmlHelper;
}
public FormBuilder<object> Form<T>(IDictionary<string, string> customizeArgs = null, FormBuilder<object> externalForm = null)
{
return new FormBuilder(_htmlHelper, typeof(T), customizeArgs, externalForm).Build();
}
}
- 现在我可以使用 class 为视图创建自定义内容,这要归功于 MyHtmlHelperAdapter
public class FormBuilder
{
private MyHtmlHelperAdapter _htmlHelper;
private readonly IStringLocalizer<SharedResources> _localizer;
private readonly LinkGenerator _linkGenerator;
private readonly IEngine _engine;
private readonly IEngineElement _element;
private readonly Type _typeDescriptor;
private readonly IDictionary<string, string> _descriptorArgs;
/* variabili per semplificare la gestione del builder */
private readonly FormBuilder<object> Form;
private readonly FormConfig Config;
private readonly IList<FormGroupConfig> Groups;
private readonly IList<FormItemConfig> Items;
private readonly IDictionary<string, string> FormOptions;
private readonly string _clientPrefix = "smtForm_{0}_";
public FormBuilder(MyHtmlHelperAdapter htmlHelper, Type typeDescriptor, IDictionary<string, string> ModelCustomizeArgs = null, FormBuilder<object> externalForm = null)
{
_htmlHelper = htmlHelper;
_localizer = _htmlHelper.provider.GetRequiredService<IStringLocalizer<SharedResources>>() ?? throw new ArgumentNullException();
_linkGenerator = _htmlHelper.provider.GetRequiredService<LinkGenerator>() ?? throw new ArgumentNullException();
_engine = _htmlHelper.provider.GetRequiredService<IEngine>() ?? throw new ArgumentNullException();
//code..
}
public FormBuilder<object> Build()
{
//code..
return Form;
}
//methods..
}