Home > front end >  Blazor : call a method without button click
Blazor : call a method without button click

Time:11-28

I am learning Razor. I have a very simple Razor component (using MudBlazor framework) in Budget.razor

@page "/budget"

<PageTitle>Budget</PageTitle>

<MudGrid>
    <MudItem xs="12" sm="6" md="4">
        <p> Hello you @HelloConsole() </p>
        </MudItem>
</MudGrid>

and a partial class in Budget.razor.cs :

namespace MyProject.Pages
{
   public partial class Budget
    {
        protected void HelloConsole()
        {
            Console.WriteLine("Hello");
        }
    }
}

I receive the error in Visual studio :

Cannot implicitly convert type 'void' to 'object'

What am I doing wrong ?

CodePudding user response:

<p> Hello you @HelloConsole() </p>

Says put the output from the method HelloConsole() here. But HelloConsole returns a void - exactly what the error says - which the renderer can't handle.

This works:

protected string HelloConsole()
{
   Console.WriteLine("Hello");
   return "I just wrote to the console";
}

Add on to answer:

To execute some code when loading the component:

protected override void OnInitialized()
{
   Console.WriteLine("Hello");
}
// or

protected override Task OnInitializedAsync()
{
   Console.WriteLine("Hello");
   return Task.CompletedTask;

}

CodePudding user response:

You are writing to the console. The Blazor markup expects an object (because it basically render a set of string). Change the code to return "Hello". That will work.

  • Related