Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a different base class in blazor page model partial declaration?

I am trying to use a pagemodel class in a client side Blazor in a way so i dont have to retype all the "base" properties

I was thinking of creating class

public partial class SomePage : BasePage
{ }

Error CS0263 Partial declarations of 'Somepage' must not specify different base classes

My base classe looks like this

 public class BasePage : ComponentBase
    {
        [Inject]
        protected NavigationManager NavigationManager { get; set; }

        [Inject]
        protected HttpClient Http { get; set; }

    }

I also tried changing adding IComponent, IHandleEvent, IHandleAfterRender so it looks like this

 public class BasePage : ComponentBase, IComponent, IHandleEvent, IHandleAfterRender

but that did not help.

Any ideas how to inherit from a base class in PageModel partial declaration?

like image 913
mko Avatar asked Dec 29 '19 10:12

mko


1 Answers

This is about how C# implements partial classes.

In SomePage.razor you will have to add

@inherits BasePage 

Like the error states, all parts of a partial class must specify the same base class (or none, then the baseclass from the other part will be used).

Your SomePage.razor file is compiled to C# first, and there the generator will by default specify ComponentBase as the base class. Since you cannot tell the generator to omit the base class you have to use @inherits to override it.

As a consequence, you can (but don't have to) shorten the behind class to

 partial class SomePage  // code-behind
 {
 }

the public modifier and the baseclass will then be taken from the generated part.

like image 198
Henk Holterman Avatar answered Sep 28 '22 06:09

Henk Holterman