在 Razor View 中,我可以访问模型状态对象:

@ViewData.ModelState

我如何在razor ViewData中注入(inject)和访问ModelStateTagHelper对象?我尝试了以下操作,但是ViewDataModelState始终为null:
public class ModelStateTagHelper : TagHelper
{
    public ViewDataDictionary ViewData { get; set; }
    public ModelStateDictionary ModelState { get; set; }

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

最佳答案

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

关于c# - 如何将ViewDataDictionary或ModelStateDictionary注入(inject)TagHelper?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39058433/

10-16 16:11