【问题标题】:Nested Blazor components in MVC applicationsMVC 应用程序中的嵌套 Blazor 组件
【发布时间】:2021-11-08 02:36:21
【问题描述】:

我已在 This Guide. 之后将 Blazor 组件添加到我现有的 MVC 应用程序中,这按预期工作,我能够让 Blazor 组件呈现,但是我无法使用 Blazor 组件创建简单列表,因为我无法获得组件嵌套正确。

我已在 Blazor 应用程序中正确呈现简单列表的以下代码;

SimpleList.blazor

<ol>
    @ChildContent
</ol>

@code {
    [Parameter]
    public RenderFragment ChildContent { get; set; }
}

SimpleListItem.blazor

<li>
    <span>@Text</span>
</li>

@code {
    [Parameter]
    public string Text { get; set; }
}

Index.razor

<SimpleList>
    <SimpleListItem Text="Item 1"></SimpleListItem>
    <SimpleListItem Text="Item 2"></SimpleListItem>
</SimpleList>

在上面显示的 blazor 应用程序中使用这些组件时,这会产生具有两个项目的有序列表的所需结果。但是,由于直接在 MVC 应用程序中使用 blazor 组件名称is not supported,我改为使用 helper 标记,目前正在执行以下操作;

Index.cshtml

<component type="typeof(Components.SimpleList)" render-mode="Server">
    <component type="typeof(Components.SimpleListItem)" render-mode="Server" param-Text="@("Item 1")"/>
    <component type="typeof(Components.SimpleListItem)" render-mode="Server" param-Text="@("Item 2")"/>
</component>

但这不起作用,列表项没有在列表中呈现,并且正在生成以下 HTML

生成的 HTML

<ol><!--!--></ol>
<li><span>Item 1</span></li>
<li><span>Item 2</span></li>

是我做错了什么还是 MVC 应用程序不支持嵌套组件?

【问题讨论】:

    标签: asp.net-core .net-core razor blazor


    【解决方案1】:

    &lt;component&gt; 标签本身不能以这种方式嵌套。它可以渲染一个单个组件(它本身可能有嵌套的 Razor 组件)。

    如果Index.razor 在这种情况下可以访问,您可以尝试

    <component type="typeof(Components.Index)" render-mode="Server">
    </component>
    

    标签助手正在渲染第一个组件SimpleList,但子内容为空,因此

    <ol><!--!--></ol>
    

    然后标签助手渲染内部项目:两个SimpleListItem引用导致

    <li><span>Item 1</span></li>
    <li><span>Item 2</span></li>
    

    【讨论】:

    • 很不幸,难道没有针对 MVC 应用程序的解决方法吗?
    • 没有。您将升级到完整的 Blazor 以获得适当的震撼。请注意,您可以拥有一个混合 MVC-Blazor 应用程序,其中包含 MVC 控制器+视图 Blazor 页面。
    • 听起来可行,这是可以集成到现有 MVC 应用程序中的东西,还是需要创建新的 Blazor 应用程序?
    • 假设它是 ASP.NET Core 并运行 .NET Core 3.1 或 NET 5+,它应该可以工作。我们的主要 Web 应用程序已从 ASP.NET(框架)升级到 .NET Core 3.1,然后我们添加了 Blazor 服务器端支持。我们有使用 MVC 的现有页面,一些 Razor 页面 (.cshtml) 和新页面创建为 Blazor (.razor) 文件。您应该创建基本的 Blazor Server 应用并将您的应用与该版本进行比较,以了解需要进行哪些更改。请放心,它确实有效。
    猜你喜欢
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2014-11-08
    • 1970-01-01
    • 2023-02-22
    相关资源
    最近更新 更多