Save components in list or array?

I have a index.razor, that has a for loop that generates let’s say 100 components (those display text, and a couple more vlaues), now i want to hava a reference of every component, is there a way to save those in a List or an array?

I tryed it myself in many ways but I get the name of the component displayed in the html.

addPdfComp is executed by a button:

public void addPdfComp(int type)
    var newComponent = new PdfComp();
    newComponent.text = "some test text";

and to display the components:

@foreach (var comp in PdfComponentsList)

see result

The component itself:

<div class="row p-1 " style="border:solid; ">
    <input type="number" class="col-2" @bind-value="_x"/>
    <input type="number" class="col-2" @bind-value="_y"/>
    <input type="text" class="col-4" @bind-value="text" />
@code {
public string text { get; set;  } = "Missing text";
public string type { get; set; } = "noone";
public int _x { get; set; } = 0;
public int _y { get; set; } = 0;

>Solution :

The default string representation for an object is the fully qualified class name for that object, which is what you’re seeing. This means that whatever PdfComp is, it doesn’t have a meaningful .ToString() implementation.

And that’s all Razor syntax really does in this case, it just emits output as a string. So @something will basically evaluate something as a string and write it to the output.

Based on a comment above:

My intention is […] to display the component itself as if i just typed: <PdfComp></PdfComp> 100 times.

An instance of PdfComp in C# code is not the same thing as an instance of <PdfComp></PdfComp> in the markup. (Though I imagine they are very closely analogous somewhere in the depths of the framework.) What you want isn’t a list of object instances, but a list of the data your view needs to render the markup.

So, structurally, more like this:

// PdfComponentsList here is a list of strings
PdfComponentsList.Add("some test text");

And then loop through it in the markup to display the elements:

@foreach (var pdf in PdfComponentsList)
    <PdfComp text="@pdf"></PdfComp>

You could also make PdfComponentsList a list of some object to hold multiple properties, for example:

PdfComponentsList.Add(new SomeObject { Text = "some test text" });

And in the markup:

@foreach (var pdf in PdfComponentsList)
    <PdfComp text="@pdf.Text"></PdfComp>

Leave a Reply