1

I am working in ASP.NET MVC 5 and am trying to post a form back to the controller. The form basically has several repeating textboxes that . I am trying to reuse the one model for each repeating form so I don't have to make a new field for each text box there is.

Model:

public class Person 
{
    public string Name { get; set; }
    public int Age { get; set; }
}

The part of my view where I am model binding text boxes (this is under @html.beginform)

@using (Html.BeginForm("PeronSave", "Home", FormMethod.Post, new { id = "PersonForm" })) 
<td>Person 1</td>
<td>@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })  </td>
<td>@Html.TextBoxFor(m => m.Age, new { @class = "form-control" })  </td>

Now I want to have several of these groups of text boxes, so there would be Person1, Person2, Person3 etc. Is there a way I can send a list of type Person back to the controller?

I have tried changing using a foreach loop in the view but it doesn't have the desired result.

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12
konkon
  • 13
  • 3
  • You can post a list of objects with an index `Name[0]`. See this question https://stackoverflow.com/q/19964553/2030565 – Jasen Dec 08 '22 at 20:43

1 Answers1

0

If you want to pass list of type of Person to the backend, You need to add index to each property. Please refer to this simple demo:

Here I use @for(xx) to create three Person inputs and add index to each property:

@model List<Person>

@using (Html.BeginForm("PeronSave", "Home", FormMethod.Post, new { id = "PersonForm" }))
{
    @for (int i = 0; i < 3; i++)
    {
        <td>Person @(i+1)</td>
        <td>@Html.TextBoxFor(m => m[i].Name, new { @class = "form-control" })  </td>
        <td>@Html.TextBoxFor(m => m[i].Age, new { @class = "form-control" })  </td>
    }

    <button type="submit">submit</button>
}

The Page looks like:

enter image description here

Then I pass it to the backend and the controller can receive data successfully.

enter image description here

Xinran Shen
  • 8,416
  • 2
  • 3
  • 12
  • 1
    Hey I found this after I posted yesterday but thank you for the answer as it does work, I have marked it. – konkon Dec 09 '22 at 14:43