You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MVC应用中嵌套Blazor组件无法正确渲染问题咨询

问题原因

你在MVC视图里嵌套<component>标签的写法是错误的。MVC提供的<component>标签辅助器只会独立渲染每个指定的Blazor组件,并不会自动将子级<component>作为父级组件的ChildContent参数传递。你写的嵌套代码本质上是三个独立渲染的Blazor组件,父组件SimpleList的ChildContent参数没有接收到任何内容,所以渲染出来的<ol>是空的,两个SimpleListItem作为独立组件直接渲染在父组件之后,就出现了你看到的结构。

MVC本身完全支持Blazor组件嵌套,只是不能通过嵌套<component>标签的方式实现,嵌套逻辑需要放到Blazor组件内部处理。


解决方案1:封装嵌套逻辑到Blazor侧(最推荐)

将组件嵌套的逻辑完全放在Blazor项目内实现,MVC视图只负责渲染最外层的包装组件即可:

  1. 新增Blazor组件PredefinedList.razor,内容如下:
<SimpleList>
    <SimpleListItem Text="Item 1"></SimpleListItem>
    <SimpleListItem Text="Item 2"></SimpleListItem>
</SimpleList>
  1. 在MVC的Index.cshtml里直接渲染这个包装组件:
<component type="typeof(Components.PredefinedList)" render-mode="Server" />

解决方案2:通过列表参数传递动态数据

如果你的列表项是动态的,需要从MVC视图传值,可以修改SimpleList组件的参数结构,取消ChildContent的使用,改成接收列表项集合,内部自行渲染子组件:

  1. 修改SimpleList.blazor代码:
<ol>
    @foreach (var item in ItemList)
    {
        <SimpleListItem Text="@item" />
    }
</ol>

@code {
    [Parameter]
    public IEnumerable<string> ItemList { get; set; } = Enumerable.Empty<string>();
}
  1. 在MVC视图中直接传递列表参数:
<component type="typeof(Components.SimpleList)" render-mode="Server" param-ItemList="@(new List<string>{"Item 1", "Item 2"})" />

内容的提问来源于stack exchange,提问作者Tom Gothorp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:51:02