0

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" />
MWD
  • 1,632
  • 2
  • 18
  • 39
  • Look here http://stackoverflow.com/questions/19964553/mvc-form-not-able-to-post-list-of-objects – DespeiL Sep 18 '16 at 20:31
  • And add pls your form code – DespeiL Sep 18 '16 at 20:33
  • Thanks DespeiL - I learnt some more from the article you linked to :) – MWD Sep 18 '16 at 20:57
  • Generate you view correctly using a `for` loop or `EditorTemplate` and using the strongly typed `HtmlHelper` methods so that your `name` attributes are always correct (refer [HTML Table to ADO.NET DataTable](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943)) –  Sep 19 '16 at 00:57

1 Answers1

2

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
Adil Mammadov
  • 8,476
  • 4
  • 31
  • 59