ElliotSchmelliot
ElliotSchmelliot

Reputation: 8362

VB MVC 4 multiple entity creation from form submit

I am creating a web application in VB.Net with MVC 4 and Entity Framework. I would like to submit a form that creates multiple entities at once. For example, if I have the simple entity...

Public Class Employee
    Public Property EmployeeID As Integer
    Public Property Name As String
End Class

In my view, I want to be able to take user input for the creation of multiple Employees at once and then post all of this data back to a controller action. Something like...

@Using Html.BeginForm("AddEmployees")
    here is input for first employee
    here is input for second employee
    etc...
End Using

It would be great if I could say in my controller action...

<HttpPost()>
Function AddEmployees(SomeCollection As Collection(Of Employee)) As ActionResult
    For Each item in SomeCollection
        do stuff with data...
    Next
    Return RedirectToAction("Index")
End Function

How should I post this chunk of data correctly and how do I access it in my controller? I looked at a related source in C# but could not replicate it.

Upvotes: 0

Views: 834

Answers (1)

Andy T
Andy T

Reputation: 9881

You would simply need to repeat the employee input fields for as many employees as you would like to have.

Name:   <input type="text" name="[0].Name" value="" /><br>
Name:   <input type="text" name="[1].Name" value="" /><br>
Name:   <input type="text" name="[2].Name" value="" /><br>
Name:   <input type="text" name="[3].Name" value="" /><br>

Once submited, the model binding would take care of populating the list of Employees and setting the Name property.

I would recommend using something like jQuery to have a button to give the option to the user to dynamically add more fields to the screen.

Upvotes: 1

Related Questions