任何人都可以帮忙解决这个问题吗?
我有一个模型
Product{ID, Name, SupplierID, Supplier}
Supplier {ID, Name}
使用 @Html.DropDownListFor
我想填充产品的 SupplierID
和 Supplier
在我使用的 ProductController
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
使用 View
(模型 => model.SupplierID、ViewBag.SupplierId 作为 SelectList)
最佳答案
我会为此使用jquery。将选定的名称添加到您的模型并将其分配给隐藏字段
@Html.HiddenFor(x => x.SelectedName, new { @class = "SelectedName" })
然后在你的脚本中
$('#SupplierID").on('change', function(){
$('.SelectedName').val($('#SupplierID :selected').text());
});
因此,每次更改下拉列表时,所选名称都会放入隐藏字段中,并且会与下拉列表中所选的 ID 一起传递回 Controller 。希望这有帮助
关于asp.net-mvc - @Html.DropDownListFor 将 ID 和值以及 ID 的不同名称一起获取到模型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19984540/