如何将 ViewDataDictionary 或 ModelStateDictionary 注入 TagHelper?

How can I inject ViewDataDictionary or ModelStateDictionary into TagHelper?

在剃须刀视图中,我可以访问模型状态对象:

@ViewData.ModelState

如何在 razor TagHelper 中注入和访问 ViewDataModelState 对象?我尝试了以下操作,但是 ViewDataModelState 始终为空:

public class ModelStateTagHelper : TagHelper
{
    public ViewDataDictionary ViewData { get; set; }
    public ModelStateDictionary ModelState { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
    }
}

可以注入IActionContextAccessor:

    public void ConfigureServices(IServiceCollection services)
    {
        //...
        services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
    }

    public class ModelStateTagHelper : TagHelper
    {
        public readonly IActionContextAccessor _accessor;

        public ModelStateTagHelper(IActionContextAccessor accessor)
        {
            _accessor = accessor;
        }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var modelState = _accessor.ActionContext.ModelState;
        }
    }

对于那些寻找 ViewData 而不是 ModelState 的人,您可以将 ViewContext 添加到您的 TagHelper

public class EmailTagHelper : TagHelper
{
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        var hasACertainKey = this.ViewContext.ViewData.ContainsKey("ACertainKey");
    }
}