asp.net-coreblazor

Can't pass a class parameter to Blazor RenderFragment


I'm working on a Blazor WebApp, .net 8.0, server only application. I'm having problems with RenderFragment.

This is the type I'm passing as a parameter to the RenderFragment delegate:

public class Temp1
{
    public string? a { get; set; }
    public string? b { get; set; }

    public Temp1 (string? a, string? b)
    {
        a = this.a;
        b = this.b;
    }
}

This is the RenderFragment definition:

public RenderFragment<Temp1> CreateButton => content => __builder => 
{
<button class="btn" onclick="@MenuOperations.CanvasMouseClick"> Button </button>
<button class="btn"> @content.a  aaa</button>
<button class="btn" onclick="@MenuOperations.CanvasMouseClick"> @content.b  bbb</button>
};  

This is where I call it:

@CreateButton(new("x", "y"))    

The problem is that when "CreateButton" executes, "content" is null but I don't see any errors using VS 2022.

Anybody know why content is null?

This is the example I used to create my code. It works.

public RenderFragment<string> SayHelloName => name => __builder =>
{
    <h1>Hello @name</h1>
};


@SayHelloName("foo")

I saw examples from other places that used a class type instead of a string type so I don't know why that would be a problem.

I tried replacing "CreateButton =>" with "CreateButton =" because I saw that code somewhere. That didn't fix it; not even sure why both versions compile correctly but that's not important.


Solution

  • It should be

            public Temp1(string? a, string? b)
            {
                this.a = a;
                this.b = b;
            }
    

    this.a refer to the property inside the class public string? a { get; set; }.