Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor Reusable RenderFragments in code with event : Cannot convert lambda expression to intended delegate type

Anyone knows why the below doesn't work? If I remove "onclick" event then it compiles & works as expected. Is that we are not allowed to use event within Reusable RenderFragments?

Env: ASP.NET Core 3.1 & Blazor Web Assembly

Thanks a lot for the help in advance!

Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type

enter image description here

@code {
    RenderFragment<(CategoryDto category, int myId)> rf =
      val => __builder =>
      {
        <h1 @onclick="()=> Console.WriteLine(val.category.Name)">Hello @val.category.Name, @val.myId</h1>
      };
}
like image 405
My Helper Avatar asked Oct 26 '25 17:10

My Helper


1 Answers

The @onclick handler in your code will ultimately be created by the EventCallbackFactory. However, that factory needs a reference to 'this' which isn't supported in field initializers - hence you are receiving this error (and probably another one regarding 'this').

The solution is pretty simple. You just need to turn the field into a property like so:

RenderFragment<(CategoryDto category, int myId)> rf => val => __builder =>
{
    <h1 @onclick="() => Console.WriteLine(val.category.Name)">Hello @val.category.Name, @val.myId</h1>
};
like image 65
Akinzekeel Avatar answered Oct 29 '25 20:10

Akinzekeel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!