Search code examples
asp.netasp.net-mvcasp.net-corerazormodel-binding

How to pass multiple objects of same model type from view to controller?


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.


Solution

  • 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