如何在ASP.NET Core ViewComponent类中访问标签内部内容?
获取ViewComponent标签内的子内容("hello"值)
嘿,这个问题我熟!要拿到包裹在<vc:Blockheader>标签中间的hello内容,其实核心是利用Razor的RenderFragment类型来传递子内容,分两种常见场景处理:
场景1:只是要把内容传递到组件视图渲染
这种情况最简单,直接在你的ViewComponent的Invoke(或InvokeAsync)方法里定义一个RenderFragment类型的参数(默认命名为ChildContent,框架会自动绑定标签内的内容):
public class BlockheaderViewComponent : ViewComponent { // 定义参数接收子内容,同时接收你的button-text和block-title public IViewComponentResult Invoke(string buttonText, string blockTitle, RenderFragment childContent) { // 把所有参数打包成视图模型传给组件视图 var vm = new BlockheaderViewModel { ButtonText = buttonText, BlockTitle = blockTitle, ChildContent = childContent }; return View(vm); } }
然后在你的组件视图(比如Views/Shared/Components/Blockheader/Default.cshtml)里直接渲染这个子内容:
@model BlockheaderViewModel <div class="block-header"> <h2>@Model.BlockTitle</h2> <button>@Model.ButtonText</button> <!-- 渲染子内容,这里就会显示"hello" --> <div class="block-content">@Model.ChildContent</div> </div>
你的调用代码完全不用改,保持原样就行:
<vc:Blockheader button-text="Create new skill" block-title="@ViewData["Title"]"> hello </vc:Blockheader>
场景2:需要在ViewComponent类中把内容转为字符串处理
如果不是要渲染,而是要在后台拿到hello这个文本值(比如做逻辑判断、存储等),就得把RenderFragment渲染成字符串,这时候要用异步方法:
public class BlockheaderViewComponent : ViewComponent { public async Task<IViewComponentResult> InvokeAsync(string buttonText, string blockTitle, RenderFragment childContent) { // 创建StringWriter来捕获渲染后的文本 using var stringWriter = new StringWriter(); // 异步渲染子内容到Writer await childContent.InvokeAsync(stringWriter); // 拿到处理后的文本(Trim去掉前后空格) string childText = stringWriter.ToString().Trim(); // 这里就可以用childText做你需要的逻辑了 var vm = new BlockheaderViewModel { ButtonText = buttonText, BlockTitle = blockTitle, ChildText = childText }; return View(vm); } }
对应的视图里如果要显示这个文本,直接用@Model.ChildText就行。
小提醒:如果你的参数名不是ChildContent,那在调用组件的时候需要显式指定,比如<vc:Blockheader ... my-custom-content="hello"></vc:Blockheader>,但默认用ChildContent是最省心的,直接写在标签中间就行。
内容的提问来源于stack exchange,提问作者Meca
相关产品推荐
相关产品推荐

