如何在Razor页面中渲染带RenderFragment参数的Blazor组件
在Razor页面中为Blazor组件传递RenderFragment参数的正确方式
我有一个Blazor组件Button.razor,代码如下:
<button params...> @ChildContent </button> @code { [Parameter] public RenderFragment ChildContent { get; set; } }
我需要在Razor页面(.cshtml)中使用这个组件,已知可以通过@(await Html.RenderComponentAsync<Button>(RenderMode.ServerPrerendered))渲染,但不知道如何正确传递RenderFragment类型的参数。
尝试的方法及问题
1. 直接传入字符串
代码:
@(await Html.RenderComponentAsync<Button>(RenderMode.ServerPrerendered, new { ChildContent = "Button text" }))
报错:
InvalidCastException: Unable to cast object of type 'System.String' to type 'Microsoft.AspNetCore.Components.RenderFragment'.
2. 通过扩展方法将字符串转为RenderFragment
先定义扩展方法:
public static class StringExtensions { public static RenderFragment ToRenderFragment(this string s) => b => b.AddContent(0, s); }
调用代码:
@(await Html.RenderComponentAsync<Button>(RenderMode.ServerPrerendered, new { ChildContent = "Button text".ToRenderFragment() }))
依然报错:
NotSupportedException: Serialization and deserialization of 'Microsoft.AspNetCore.Components.RenderFragment' instances are not supported.
3. 使用<component>标签
代码:
<component type="typeof(Button)" render-mode="ServerPrerendered"> Button text </component>
渲染结果不符合预期:
<button></button> Button text
预期结果应为:
<button> Button text </button>
注:按钮仅为简化示例,直接在.cshtml中写原生标记会导致代码重复,因此需要找到正确的实现方式。
内容的提问来源于stack exchange,提问作者wujido
相关产品推荐
相关产品推荐

