MVC更新帖子

时间:2016-09-18 20:20:06

标签: c# asp.net-mvc entity-framework asp.net-mvc-5

我正在尝试一次更新多个记录,但我的模型始终为空。

这可以更新单个记录。交= 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);
    }

我需要做这样的事情来更新多个记录,但模型总是为空。交= 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);
    }

更新 - 修正:

对于遇到同样问题的其他人,我的表单字段如下:

<input type="hidden" name="AttendeeId[@i]" id="AttendeeId[@i]" value="@item.AttendeeId" />

但要使其正常工作,我必须将表单字段更新为:

<input type="hidden" name="[@i].AttendeeId" id="[@i].AttendeeId" value="@item.AttendeeId" />

1 个答案:

答案 0 :(得分:1)

问题不在你的行动中,可能在你看来。如您所述,您发布的数据如下:

AttendeeId[0]=79 
ArrivedAttendees[0]=3
AttendeeId[1]=80
ArrivedAttendees[1]=5

要使MVC框架能够正确绑定模型,发布的数据应如下所示:

[0].AttendeeId=79 
[0].ArrivedAttendees=3
[1].AttendeeId=80
[1].ArrivedAttendees=5