How to use Bindproperty in variables where names are dynamic in . net-core Razor pages

Asked

Viewed 281 times

1

In Asp.net core Razor pages to pass data from a form declared as follows:

[BindProperty]
public int NMembro1 { get; set; }

Where on the form side the tag input is stated as follows:

<input style="max-width:5.75rem; border: 1px solid #ccc; border-radius: 3px;" name="NMembro1' type="number" min="1">

Then I realize the attribute name tag input has the same name as the variable in backend. name="NMembro1'

 [BindProperty]
  public int NMembro1 { get; set; }

After the framing step explain the problem:

This input tag is created dynamically in, then to get the data from view I need to dynamically declare these variables.

Follow the code below

 let html = "";
 for (var i = 0; i < arr.length; i++)
 {
   html += '<input style="max-width:5.75rem; border: 1px solid #ccc; border-radius: 3px;" name="NMembro' + i +'" type="number" min="1">';
 }

Something that worked was to declare the variables in the following form:

[BindProperty]
public int NMembro1 { get; set; }

[BindProperty]
public int NMembro2 { get; set; }

...

But the problem remains: If I don’t know how many variables are generated in as I can state them this way on the side of ?

After reading some documentation I tried something of this kind

 [BindProperty]
 public Dictionary<string, object> NMembro { get; set; }

But it didn’t help because I still couldn’t bid

1 answer

1


[BindProperty] 
public List<string> NMembro { get; set; } 

Data is being generated using thus, the data after generated are placed with to manipulate and generate the , however this reference to only serves as a framework for the question in question.

Follow the code below

    let html = "";
    for(var i = 0; i < 10; i++;)
    {
       html += '<input style="max-width:5.75rem; border: 1px solid #ccc; border-radius: 3px;"
       name="' + NMembro[i]+'" type="number" min="1">'
    }

Final explanation

The problem occurred because we needed to bind a property and the name of that property was generated in

 NMembro[i]

Then to the [BindProperty] run on the server-side side we declare the variable with the type List as follows public List<string> NMembro { get; set; }

I now leave for last a useful reference that I found on the internet to answer this question https://www.learnrazorpages.com/razor-pages/model-binding#Binding-Complex-Collections https://www.red-gate.com/simple-talk/dotnet/asp-net/model-binding-asp-net-core/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.