blazorblazor-server-sideblazor-webassemblymudblazor

Blazor Inheritance and Code-behind Structure


I want to keep my Blazor component's logic in the code-behind file (i.e., .razor.cs) and only have the UI markup in the .razor file. To achieve this, I’ve created a base class (CustomBasePage) that contains some shared logic.

In the code-behind (.razor.cs), I want to inherit from this CustomBasePage. However, I’m getting an error:

Partial declarations of 'CustomerDetails' must not specify different base classes.

Here’s what I’ve done so far:

In the CustomerDetails.razor file, I’ve removed any @inherits directive so that only the markup is present. In the CustomerDetails.razor.cs file, I’ve made the CustomerDetails class inherit from CustomBasePage. Despite this, I still receive the error. I’ve tried cleaning the solution, ensuring there’s no @inherits directive in the .razor file, and even checked for other possible conflicting partial class declarations.

This is the code of CustomerPage.razor.cs:

    public partial class CustomerDetails : BasePage {
    ...
        protected override async Task OnInitializedAsync(){
SetMenu()//I want to call the function from the basePage.. PROBLEM
} 

    }

For the CustomerPage.razor I dont inherit anything

and for the BasePage I have this code :

public class BasePage : ComponentBase
{
    [Inject] private IJSRuntime JSRuntime { get; set; }
    [Inject] private AppStateService AppState { get; set; }
    [Inject] private IMenuManager _menuManager { get; set; }
    [Inject] private NavigationManager NavigationManager { get; set; }

    protected new void StateHasChanged() => base.StateHasChanged();

    protected async Task SetMenu()
    {
        Console.WriteLine("PAGE INITIALIAZE");

        //Implementation
        await Task.CompletedTask;
    }
}

I need to access SetMenu in the code behind


Solution

  • I’ve removed any @inherits directive so that only the markup is present.

    when you do that then Blazor will default to inheriting from the ComponentBase class.

    Either specify the same baseclass in both files or use only an @inherits. In your case:

    CustomerPage.razor:

     @inherits BasePage 
    

    CustomerPage.razor.cs:

    public partial class CustomerPage {
       ...
    }