在razor视图中,我可以访问模型状态对象:
prototype
如何在剃刀@ViewData.ModelState
中注入和访问ViewData
或ModelState
个对象?我尝试了以下操作,但TagHelper
和ViewData
始终为空:
ModelState
答案 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;
}
}