Reputation: 1198
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 ?
Upvotes: 1
Views: 1817
Reputation: 19725
You need to execute as annonymous lambda otherwise it will expect a string/object return:
This should work:
@page "/budget"
<PageTitle>Budget</PageTitle>
<MudGrid>
<MudItem xs="12" sm="6" md="4">
<p> Hello you @(() => HelloConsole()) </p>
</MudItem>
</MudGrid>
protected void HelloConsole()
{
Console.WriteLine("Hello");
}
Upvotes: 1
Reputation: 30450
<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";
}
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;
}
Upvotes: 3
Reputation: 2080
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.
Upvotes: 0