【问题标题】:How do I render a blazer component on the server and get the generated HTML?如何在服务器上渲染 blazer 组件并获取生成的 HTML?
【发布时间】:2021-10-21 18:50:12
【问题描述】:

我创建了一个 Blazor 组件,用于在我的 Blazor WASM 应用程序中呈现 SVG 图。我想知道如何/是否可以在服务器上重用该组件来呈现其 HTML。

I am currently generating HTML using the razor view engine and converting the HTML into a PDF document。我打算将 blazor 组件中的 HTML 放入视图中,并将其转换为 PDF。

【问题讨论】:

  • @NicolaBiada 这没用。
  • 不能直接使用组件标签助手放到视图中吗?
  • @MisterMagoo 是的,这很有效,而且更容易

标签: blazor


【解决方案1】:

Magoo 先生向我指出了一种更好的方法。 只需在视图中使用component tag helper

<component type="typeof(MyComponent)" render-mode="Static" param-MyComponentParameter="Model.MyComponentParameter" />

旧答案:

我设法弄清楚了基础并做了一个扩展方法。

public static class HttpContextExtensions
{
    /// <summary>
    /// Renders the HTML of the blazor component.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    public static async Task<string> RenderComponentAsync<T>(this HttpContext httpContext) where T : IComponent
    {
        var componentTagHelper = new ComponentTagHelper
        {
            ComponentType = typeof(T),
            RenderMode = RenderMode.Static,
            Parameters = new Dictionary<string, object>(), //TODO: Overload and pass in parameters
            ViewContext = new ViewContext { HttpContext = httpContext },
        };

        var tagHelperContext = new TagHelperContext(
            new TagHelperAttributeList(),
            new Dictionary<object, object>(),
            "uniqueid");

        var tagHelperOutput = new TagHelperOutput(
            "tagName",
            new TagHelperAttributeList(),
            (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(new DefaultTagHelperContent()));

        await componentTagHelper.ProcessAsync(tagHelperContext, tagHelperOutput);

        using var stringWriter = new StringWriter();

        tagHelperOutput.Content.WriteTo(stringWriter, HtmlEncoder.Default);

        return stringWriter.ToString();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多