5

In razor views I can access model state object:

@ViewData.ModelState

How can i inject and access ViewData or ModelState objects in razor TagHelper? I tried the following, however the ViewData and ModelState are always null:

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

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

2 回答 2

17

对于那些正在寻找ViewData而不是 的人ModelState,您可以ViewContextTagHelper.

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");
    }
}
于 2016-09-13T13:32:49.610 回答
5

您可以注入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;
        }
    }
于 2016-08-20T20:53:59.443 回答