如何将ViewDataDictionary或ModelStateDictionary注入TagHelper?

时间:2016-08-20 20:27:25

标签: c# asp.net-core asp.net-core-tag-helpers

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

prototype

如何在剃刀@ViewData.ModelState 中注入和访问ViewDataModelState个对象?我尝试了以下操作,但TagHelperViewData始终为空:

ModelState

2 个答案:

答案 0 :(得分:5)

对于那些寻找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");
    }
}

答案 1 :(得分:3)

您可以注入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;
        }
    }