任何人都可以帮助如何做到这一点吗?
我有一个模型
Product{ID, Name, SupplierID, Supplier}
Supplier {ID, Name}
使用我想填充产品的SupplierID
和Supplier
@Html.DropDownListFor
在我使用的产品控制器中
public ActionResult Edit(Guid id)
{
Product product = db.products.Find(id);
if (product == null)
{
return HttpNotFound();
}
ViewBag.SupplierId = new SelectList(db.Suppliers, "ID", "Name", product.SupplierID );
return View(customer);
}
[HttpPost]
public ActionResult Edit(Customer customer)
{
if (ModelState.IsValid)
{
db.Entry(customer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
在db.SaveChanges
,它抱怨Supplier
NULL
使用视图(模型 =>模型。SupplierID, ViewBag.SupplierId as SelectList)
我会使用jquery来实现这一点。 将所选名称添加到模型并将其分配给隐藏字段
@Html.HiddenFor(x => x.SelectedName, new { @class = "SelectedName" })
然后在您的脚本中
$('#SupplierID").on('change', function(){
$('.SelectedName').val($('#SupplierID :selected').text());
});
因此,每次更改下拉列表时,所选名称都会放在隐藏字段中,并且该名称将与下拉列表中的所选id一起传递回控制器。 希望这有帮助