我正在创建一个用于预订酒店客房客人的应用程序。我正在尝试在ReservationViewModel包含的列表中编辑来宾。在GET上,我成功地将带有两个空Guest项目的ViewModel传递给View,并在View中创建了编辑器。每当我发回ReservationVM并尝试读取它们时,列表就会显示为空。我已按照建议将我的foreach循环更改为for循环,但这似乎不起作用。该列表似乎是空的,每当尝试从列表中读取但没有任何输出时,我都会尝试打印一条消息。
这是我的GET:
[HttpGet]
public ActionResult Edit2(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Reservation reservation = resRepo.GetReservationByID(id);
ReservationVM reservationVM = new ReservationVM(0);
for (int i = 0; i < reservation.amount_people; i++)
{
reservationVM.guests.Add(new Guest());
}
foreach (Guest guest in reservationVM.guests)
{
guest.name = " ";
guest.zipcode = " ";
guest.housenumber = 0;
guest.suffix = "";
guest.email = " ";
guestRepo.AddGuest(guest);
}
guestRepo.Save();
reservationVM.date = (DateTime)reservation.date;
reservationVM.amount_people = (int)reservation.amount_people;
reservationVM.ID = reservation.ID;
reservationVM.room_ID = (int)reservation.room_ID;
if (reservation == null)
{
return HttpNotFound();
}
return View(reservationVM);
}
这是我的帖子:
[HttpPost]
public ActionResult Edit2(ReservationVM reservationVM)
{
if (ModelState.IsValid)
{
//Get reservation
Reservation reservation = resRepo.GetReservationByID(reservationVM.ID);
//Update values in model
reservation.date = reservationVM.date;
reservation.amount_people = reservationVM.amount_people;
reservation.ID = reservationVM.ID;
reservation.room_ID = reservationVM.room_ID;
Debug.WriteLine(reservation.ID);
//Update to DB and save changes
resRepo.UpdateReservation(reservation);
resRepo.Save();
foreach(Guest guest in reservationVM.guests)
{
Debug.WriteLine("hello");
guestRepo.UpdateGuest(guest);
reservation.Guests.Add(guest);
}
guestRepo.Save();
db.SaveChanges();
return RedirectToAction("Index");
}
return View(reservationVM);
}
编辑:将ViewModel内部的列表从View传递到ASP.NET MVC中的控制器吗?
答案 0 :(得分:0)
您的代码对我来说似乎还可以,请猜测您的操作可能需要添加前缀
[HttpPost]
public ActionResult Edit2([Bind(Include = "guests")]DataReservationVM reservationVM)
{
.....
}
答案 1 :(得分:0)
我修复了!谢谢您的帮助。我的问题是绑定。添加了[Bind(Include ="date, amount_people,ID,room_ID,guests")]
并为Guest对象创建局部视图似乎有助于绑定。