当前这样输出 ViewComponent
public IActionResult AggTopPosts()
{
return ViewComponent(nameof(AggTopPosts));
}
现在想将这个 ViewComponent 输出为字符串,也就是渲染(render)这个 ViewComponent 并将渲染结果保存在字符串中,请问如何实现?
通过下面的代码解决了
public async Task<IActionResult> AggTopPosts()
{
using var writer = new StringWriter();
var viewContext = new ViewContext(ControllerContext, NullView.Instance, ViewData, TempData, writer, new HtmlHelperOptions());
var helper = HttpContext.RequestServices.GetRequiredService<IViewComponentHelper>();
(helper as IViewContextAware)?.Contextualize(viewContext);
var result = await helper.InvokeAsync(typeof(AggTopPosts), null);
result.WriteTo(writer, HtmlEncoder.Default);
return Content(writer.ToString());
}
NullView 的实现
public class NullView : IView
{
public static readonly NullView Instance = new();
public string Path => string.Empty;
public Task RenderAsync(ViewContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
return Task.CompletedTask;
}
}
参考: