Blazor 服务器 - “代码隐藏”模式:OnInitializedAsync():找不到合适的方法来覆盖

DrG*_*iff 11 code-behind blazor blazor-server-side

我有一个 Blazor(服务器)应用程序,它运行得非常好,并且遵守Microsoft.CodeAnalysis.FxCopAnalyzers和设置的所有规则StyleCop.Analyzers

一个大幅削减的剃刀页面如下:

@inherits OwningComponentBase<MyService>
@inject IModalService ModalService
@inject IJSRuntime JSRuntime

// UI code

@code
{
    private readonly CancellationTokenSource TokenSource = new CancellationTokenSource();
    ElementReference myElementReferenceName;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await this.myElementReferenceName.FocusAsync(this.JSRuntime);
    }

    protected override async Task OnInitializedAsync()
    {
        ....
    }

    public void Dispose()
    {
        this.TokenSource.Cancel();
    }

    protected void ShowModalEdit(object someObject)
    {
        .....
        Modal.Show<MyPage>("Edit", parameters);
    }
}
Run Code Online (Sandbox Code Playgroud)

注意#1:我@inherits OwningComponentBase<MyService>根据Daniel Roth 的建议使用

注意#2:我正在使用Chris Sainty 的 Modal 组件组件

但是,当我尝试将所有代码从该@code {...}部分移动到“代码隐藏”部分类(“MyPage.razor.cs”)时,我遇到了以下错误......

“MyPage”不包含“Service”的定义,也没有可访问的扩展方法“Service”接受 .....

'MyPage.OnAfterRenderAsync(bool)':找不到合适的方法来覆盖

'MyPage.OnInitializedAsync()':找不到合适的方法来覆盖

类型“MyPage”不能用作泛型类型或方法“IModalService.Show(string, ModalParameters, ModalOptions)”中的类型参数“T”。没有从“MyPage”到“Microsoft.AspNetCore.Components.ComponentBase”的隐式引用转换。

建议?

And*_*löw 14

总长DR

确保razor.cs文件中的命名空间正确

更长的解释

就我而言,当我将类放入错误的命名空间时,我收到了此错误。该page.razor.cs文件与该文件位于同一目录中,并且包含2019 年 10 月更新所接受的page.razor部分类。

但是,即使文件位于path/to/dirpage.razor.cs但其命名空间为path.to.another.dir,这会导致抛出此错误。只需更改名称空间即可path.to.dir为我修复此错误!


Mih*_*myh 9

MyPage.razor.cs应该从ComponentBaseclass继承,你Mypage.razor应该从MyPage.razor.cs.

在您的“代码隐藏”类中,您应该[Inject]为您正在注入的每个服务使用属性,并使它们至少protected成为能够在您的剃刀组件中使用它们的属性。

下面是我的一个测试应用程序的示例,请注意它使用 .net-core 3.0,在 3.1 中您可以使用部分类。

Index.razor

@page "/"
@inherits IndexViewModel

<div class="row">
    <div class="col-md">

        @if (users == null)
        {
            <p><em>Hang on while we are getting data...</em></p>
        }
        else
        {
            <table class="table">
                <thead>
                    <tr>
                        <th class="text-danger">Id</th>
                        <th class="text-danger">Username</th>
                        <th class="text-danger">Email</th>
                        <th class="text-danger">FirstName</th>
                        <th class="text-danger">LastName</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var user in users)
                    {
                        <tr>
                            <td>@user.Id</td>
                            <td>@user.Username</td>
                            <td>@user.Email</td>
                            <td>@user.FirstName</td>
                            <td>@user.LastName</td>
                        </tr>
                    }
                </tbody>
            </table>
        }
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

索引视图模型.cs

public class IndexViewModel : ComponentBase, IDisposable
{
    #region Private Members
    private readonly CancellationTokenSource cts = new CancellationTokenSource();
    private bool disposedValue = false; // To detect redundant calls

    [Inject]
    private IToastService ToastService { get; set; }
    #endregion

    #region Protected Members
    protected List<User> users;

    [Inject] IUsersService UsersService { get; set; }

    protected string ErrorMessage { get; set; }

    #endregion

    #region Constructor

    public IndexViewModel()
    {
        users = new List<User>();
    }

    #endregion

    #region Public Methods


    #endregion

    #region Private Methods

    protected override async Task OnInitializedAsync()
    {
        await GetUsers().ConfigureAwait(false);
    }

    private async Task GetUsers()
    {
        try
        {
            await foreach (var user in UsersService.GetAllUsers(cts.Token))
            {
                users.Add(user);
                StateHasChanged();
            }
        }
        catch (OperationCanceledException)
        {
            ShowErrorMessage($"{ nameof(GetUsers) } was canceled at user's request.", "Canceled");
        }

        catch (Exception ex)
        {
            // TODO: Log the exception and filter the exception messages which are displayed to users.
            ShowErrorMessage(ex.Message);
        }
    }

    private void ShowErrorMessage(string message, string heading ="")
    {
        //ErrorMessage = message;
        //StateHasChanged();
        ToastService.ShowError(message, heading);
    }

    private void ShowSuccessMessage(string message, string heading = "")
    {
        ToastService.ShowSuccess(message, heading);
    }

    protected void Cancel()
    {
        cts.Cancel();
    }
    #endregion

    #region IDisposable Support

    protected virtual void Dispose(bool disposing)
    {
        if (!disposedValue)
        {
            if (disposing)
            {
                cts.Dispose();
            }

            disposedValue = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
        // TODO: uncomment the following line if the finalizer is overridden above.
        // GC.SuppressFinalize(this);
    }
    #endregion

}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • 我的原因是说找不到方法、没有要重写的方法等,是因为我没有将命名空间更正为与 *.razor* 视图相同。 (2认同)

Dev*_*sse 6

当我使用部分类方法时,我遇到了这个错误,并且我试图构建 Identity。我改用基类方法就解决了。

我在添加组件后使用的部分类,例如,我添加了一个用于注入服务的MyComponent类:MyComponent.razor.cs

public BuildingServices Services { get; set; }
Run Code Online (Sandbox Code Playgroud)

对于添加后的基类方法MyComponent,我添加了一个类来MyComponent.razor.cs更改类名并使其继承componentBase

MyComponentBase : ComponentBase
Run Code Online (Sandbox Code Playgroud)

我把它放在顶部MyComponent.razor

@inherits MyComponentBase
Run Code Online (Sandbox Code Playgroud)

使用 protected 关键字使您的方法可访问。