我使用断点调试它我的ClientsId总是为空并显示在我的支付索引上始终是我的Dropdownlist的第一个值
型号:
public class Payments
{
[Key]
public int PaymentsId { get; set; }
public int ClientId { get; set; }
public virtual Client Client { get; set; }
}
视图模型:
public class PaymentsViewModel
{
[Required(ErrorMessage = "Please select a client")]
[Display(Name = "Client")]
public int SelectedClient { get; set; }
public IEnumerable<SelectListItem> Client { get; set; }
}
获取控制器:
public ActionResult Create(Payments model)
{
var liste= new PaymentsViewModel
{
Clients = new SelectList(db.ClientList, "ClientId", "ClientName")
};
return View(liste);
}
POST控制器:
public ActionResult Create([Bind(Include = "....")] PaymentsViewModel model)
{
if (ModelState.IsValid)
{
model.PaymentsCreate();
return RedirectToAction("Index", "Payments");
}
return View(model);
}
创建视图:
@Html.DropDownListFor(m => m.SelectedClient, Model.Clients, "-Please select-", new { @class = "form-control" })
</div>
</div>
-------------------------------------------- UPDATE-- ------------------------------------------------- < / p>
编辑控制器(GET):
public ActionResult Edit(int? id, PaymentsViewModel model)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Payments payments = db.PaymentsList.Find(id);
if (payments == null)
{
return HttpNotFound();
}
return View();
}
编辑控制器(POST)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PaymentsId,Paymentnumber,PaymentDate,Amount,Discount,Reference,Total")] Payments payments)
{
if (ModelState.IsValid)
{
db.Entry(payments).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(payments);
}
答案 0 :(得分:0)
您应该在PaymentsCreate函数的model.SelectedClient中添加ClientsId初始化,例如:ClientsId = model.SelectedClient。然后你需要将SelectedClient字符串添加到Create(post)方法中的属性枚举到Bind(包含....属性