Home > database >  Save components in list or array?
Save components in list or array?

Time:07-27

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";
    PdfComponentsList.Add(newComponent);
}

and to display the components:

@foreach (var comp in PdfComponentsList)
{
        <div>@comp</div>
}

result: see result

Edit: The component itself:

<div  style="border:solid; ">
<h5>TextComponent</h5>
<div>
    <label>X</label>
    <input type="number"  @bind-value="_x"/>
    <label>Y</label>
    <input type="number"  @bind-value="_y"/>
    <label>Text</label>
    <input type="text"  @bind-value="text" />
</div>
@code {
[Parameter]
public string text { get; set;  } = "Missing text";
[Parameter]
public string type { get; set; } = "noone";
[Parameter]
public int _x { get; set; } = 0;
[Parameter]
public int _y { get; set; } = 0;
}

CodePudding user response:

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>
}
  • Related