0
我有一個viewmodel,有兩個屬性,一個是POCO類,另一個是double,當控制器構建併發送viewmodel時,所有值都存在並在頁面上工作。當我POST視圖模型時,設置了double值,並且該對象存在,但內部的POCO類爲null,而不是在發送該對象時。ViewModel對象child在POST上爲空
在下面的例子中,爲什麼ticket.flight
null在POST的viewmodel對象上?
視圖模型:
public class PayViewModel
{
public virtual Ticket ticket { get; set; }
public double amountToPay = 0.0;
[Display(Name = "Amount To Pay")]
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)]
public double AmountToPay
{
get
{
return amountToPay;
}
set
{
amountToPay = value;
}
}
}
控制器方法:
// GET: Tickets/Pay/5
public ActionResult Pay(int? id)
{
if (id == null)
{
return RedirectToAction("Index");
}
Ticket ticket = db.tickets.Find(id);
if (ticket == null)
{
return RedirectToAction("Index");
}
PayViewModel viewModel = new PayViewModel();
viewModel.ticket = ticket;
return View(viewModel);
}
// POST: Tickets/Pay/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Pay([Bind(Include = "AmountToPay,ticket,ticket.flight")]PayViewModel viewModel)
{
if (ModelState.IsValid)
{
viewModel.ticket.AmountPaid += viewModel.AmountToPay;
if (viewModel.ticket.AmountPaid >= viewModel.ticket.flight.ticketPrice)
{
viewModel.ticket.status = TicketStatusType.CONFIRMED;
}
db.Entry(viewModel.ticket).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel.ticket);
}
查看代碼 - https://gist.github.com/JonFriesen/f511a91b8e9a90c1b23c
你還可以添加查看代碼嗎? – dotnetom
@dotnetom在GitHub GIST中添加了一個鏈接到視圖代碼(出於某種原因,StackOverflow不會讓我發佈它)。感謝您的回覆 – JonFriesen
刪除'[綁定(包括=「金額支付,票證,ticket.flight」)]位。當你這樣做會發生什麼? –