DrGriff
DrGriff

Reputation: 4916

Blazor Server - 'Code Behind' pattern: OnInitializedAsync(): no suitable method found to override

I have a Blazor (Server) application which runs perfectly fine, and which adheres to all rules set by Microsoft.CodeAnalysis.FxCopAnalyzers and StyleCop.Analyzers.

A heavily cut-down razor page is as follows:

@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);
    }
}

Note#1: I used @inherits OwningComponentBase<MyService> based on Daniel Roth's suggestion

Note#2: I am using the Chris Sainty's Modal component component

However, when I try to move all the code from the @code {...} section to a"Code Behind" partial class ("MyPage.razor.cs"), then I run into the following errors....

'MyPage' does not contain a definition for 'Service' and no accessible extension method 'Service' accepting .....

'MyPage.OnAfterRenderAsync(bool)': no suitable method found to override

'MyPage.OnInitializedAsync()': no suitable method found to override

The type 'MyPage' cannot be used as type parameter 'T' in the generic type or method 'IModalService.Show(string, ModalParameters, ModalOptions)'. There is no implicit reference conversion from 'MyPage' to 'Microsoft.AspNetCore.Components.ComponentBase'.

Suggestions?

Upvotes: 25

Views: 29120

Answers (12)

Frank Thomas
Frank Thomas

Reputation: 380

My error came up slightly different, but because this thread on Stack overflow is the #1 listing in the search engines on it, I'm posting my error to help the next fellow...

My error message that only came up on azure, not in visual studio was,

OnInitializedAsync error ExpectedStartOfValueNotFound, \u003C Path: $ | LineNumber: 0 | BytePositionInLine: 0."

What I discovered that I had done was pretty silly. When I initially setup the OnInitialized method, I used the non-async version. The moment I put in a line into the method to perform an awaited command, visual studio plugged in the async into the method signature line.

I hadn't put in the proper method OnInitialized'Async' method as part of the call and of course, the compiler doesn't throw and error because the method was still returning void, which is legal. But Azure did not like it and throws the error message into the logs as mentioned above. Why Visual Studio doesn't catch this, I'm unsure why.

So watch out when setting up your lifecycle calls for a blazor page. The minute you perform an awaited call, you need to ensure you call the proper lifecycle method, or you will waste hours like I've just done to find a really silly error.

//old code
protected override async void OnInitialized()

//proper code
protected override async Task OnInitializedAsync()

Upvotes: 0

iw bas
iw bas

Reputation: 1

I had the same issue when using MAUI Blazor Hybrid project.Partial class approach was working in one component and was not working on the one I recently added. I could not find any issues with code, therefore, I finally restarted Visual Studio Professional 2022 (17.9.4). Once Visual Studio reopened, error went away.

Upvotes: 0

I have Blazor .net 7 VS 2022. I got same issues, I Created new folder and copied all files one by one into new folder(Here namespace is updated) and issues resolved. Thank you, Eugine.

Upvotes: 0

Mohammad Komaei
Mohammad Komaei

Reputation: 9676

MyComponent.razor file:

<h1>@Message</h1>

MyComponent.razor.cs file:

using Microsoft.AspNetCore.Components;

namespace MyProject.Client.Shared;

public class MyComponent : ComponentBase
{
    string Message = "Hello";
}

somtime visual studio steel show error in Error List window. for making sure you have error or not build the blazor project.

Upvotes: 0

Jean Poulin
Jean Poulin

Reputation: 21

It's the type of error that can have multiple cause. In my case it was so weird that I thought what I had changed recently and it was an install of more recent .Net 7 SDK. I desinstalled it leaving the original .NET installed with VS 2022 and everything now compiles instead of 69 error of this kind.

Upvotes: 0

ilya_i
ilya_i

Reputation: 333

What did the trick for me was dragging the .razor file into Shared folder and dragging it back to the original folder. As per spmoran-blazor's answer on GitHub

Upvotes: 0

DevCisse
DevCisse

Reputation: 160

I came across this error when I used partial class approach, and I was trying to scaffold Identity. I changed to base class approach it was resolved.

Partial class I was using after adding a component say MyComponent, I added a class to MyComponent.razor.cs for injecting services:

public BuildingServices Services { get; set; }

For base class approach after adding MyComponent, I added a class to MyComponent.razor.cs change the class name and make it inherit from componentBase:

MyComponentBase : ComponentBase

And I placed this at the top of MyComponent.razor:

@inherits MyComponentBase

Use protected keyword to make your methods accessible.

Upvotes: 7

user3116631
user3116631

Reputation: 425

I found this when upgrading to 6.0. I had to switch from using base classes to using partial classes!

Upvotes: 0

Craig D.
Craig D.

Reputation: 41

It took two days of cleaning, rebuilding, ... and it turned out to be a cut and paste error. I copied the razor file from another, similar class, and left this at the top by mistake:

@inject Microsoft.Extensions.Localization.IStringLocalizer<Person> localizer

'Person' was the wrong class, it wasn't defined by any of the include statements. For some strange reason the only error was "OnInitialized() No method found to override."

Upvotes: 0

Mihaimyh
Mihaimyh

Reputation: 1420

Your MyPage.razor.cs should inherit from ComponentBase class and your Mypage.razor should inherit from MyPage.razor.cs.

In your "code-behind" class you should use [Inject] attribute for every service you are injecting and make them at least protected properties to be able to use them in your razor components.

Below is an example from one of my testing apps, please note this uses .net-core 3.0, in 3.1 you can use partial classes.

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>

IndexViewModel.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
}

Upvotes: 17

nbt1032
nbt1032

Reputation: 51

All the above points are very true. FWIW, and just to add a weird thing that I was finding with this issue; I could not get that error to go away. Everything was declared as it should be. Once you have ruled out all potential coding issues, I have found exiting VS, coming back in, and rebuilding clears it up. It is almost like VS just will not let go of that error.

Upvotes: 1

Andreas Forsl&#246;w
Andreas Forsl&#246;w

Reputation: 2738

TLDR

Make sure the namespace in your razor.cs file is correct

Longer explanation

In my case, I got this error when I put the class in the wrong namespace. The page.razor.cs file was in the same directory as the page.razor file and it contained a partial class as accepted by the October 2019 update.

However, even though the files were located in path/to/dir, page.razor.cs had a namespace of path.to.another.dir, which led to this error being thrown. Simply changing the namespace to path.to.dir fixed this error for me!

Upvotes: 18

Related Questions