Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inject ViewDataDictionary or ModelStateDictionary into TagHelper?

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)
    {
    }
}
like image 474
Mariusz Jamro Avatar asked Aug 20 '16 20:08

Mariusz Jamro


2 Answers

For those looking for the ViewData and not the ModelState, you can add the ViewContext to your 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");
    }
}
like image 62
René Sackers Avatar answered Nov 20 '22 00:11

René Sackers


You can inject 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;
        }
    }
like image 36
adem caglin Avatar answered Nov 20 '22 00:11

adem caglin