Reputation: 1642
I am trying to update multiple records at once but my model is always null.
This works to update a single record. Post=AttendeeId=79&ArrivedAttendees=3
public async Task<ActionResult> UpdateArrivalNumbers(ArrivedAttendeesVM vm)
{
var query = db.HorseRidingBookingAttendees.Find(vm.AttendeeId);
query.ArrivedAttendees = vm.ArrivedAttendees;
db.Entry(query).State = EntityState.Modified;
await db.SaveChangesAsync();
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
I need to do something like this to update multiple records but the model is always null. Post=AttendeeId[0]=79&ArrivedAttendees[0]=3&AttendeeId[1]=80&ArrivedAttendees[1]=5
public async Task<ActionResult> UpdateArrivalNumbers(List<ArrivedAttendeesVM> vm)
{
foreach (var item in vm)
{
var query = db.HorseRidingBookingAttendees.Find(item.AttendeeId);
query.ArrivedAttendees = item.ArrivedAttendees;
db.Entry(query).State = EntityState.Modified;
}
await db.SaveChangesAsync();
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
UPDATE - FIXED:
For anyone else having the same problem I had my form fields like:
<input type="hidden" name="AttendeeId[@i]" id="AttendeeId[@i]" value="@item.AttendeeId" />
But to get it working I had to update my form fields to:
<input type="hidden" name="[@i].AttendeeId" id="[@i].AttendeeId" value="@item.AttendeeId" />
Upvotes: 0
Views: 987
Reputation: 8696
The problem is not in your action, probably it is in your view. As you stated your posted data is as following:
AttendeeId[0]=79
ArrivedAttendees[0]=3
AttendeeId[1]=80
ArrivedAttendees[1]=5
For MVC framework to be able to correctly bind your model, posted data should be as following:
[0].AttendeeId=79
[0].ArrivedAttendees=3
[1].AttendeeId=80
[1].ArrivedAttendees=5
Upvotes: 2