剃刀组件标签帮手实际上未加载剃刀组件

时间:2020-07-22 20:31:46

标签: razor blazor

我一直按照this guide中的步骤在我的Razor应用程序中设置Blazor组件。我完成了该指南“准备应用程序”部分中的所有步骤,修改了_Layout.cshtml和Startup.cs文件并添加了_Imports.razor文件。为了测试这一点,我只是尝试实现一个基本的计数器组件。

我将以下代码添加到MyApp / Components / Counter.razor:

<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    [Parameter]
    public int InitialValue { get; set; }

    private void IncrementCount() => currentCount++;

    protected override void OnParametersSet()
    {
        currentCount = InitialValue;
    }
}

然后在MyApp / Pages / Counter.cshtml中我有这个:

@page
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Web
@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.JSInterop
@using MyApp
@using MyApp.Components

//This does not work--it appears exactly like this in the HTML when the page loads
<component type="typeof(Counter)" render-mode="ServerPrerendered" />

//this works as expected and loads the razor component
@(await Html.RenderComponentAsync<Counter>(RenderMode.ServerPrerendered))

请注意,我从_Imports.razor文件中复制了所有using指令,以查看是否可以解决问题,但这并没有什么不同。我的理解是RenderComponentAsync函数已经过时,并且“ component”标签助手是使用剃刀组件的当前方法。我也更喜欢使用该语法,因为它更容易传递参数。有谁知道我要让它正常工作所缺少的东西?

1 个答案:

答案 0 :(得分:1)

很高兴,经过数小时的处理之后,我意识到我的应用程序在Net Core 3.0上,并且标签助手仅在3.1+中可用。将MyApp.csproj更新为3.1即可解决此问题:

<TargetFramework>netcoreapp3.1</TargetFramework>