2

Can anyone help on how to do this please?

I have a model

Product{ID, Name, SupplierID, Supplier}
Supplier {ID, Name}

using a @Html.DropDownListFor I would like to populate both the SupplierID and the Supplier of the product

in the ProductController I use

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);
}

In db.SaveChanges it complains that Supplier is NULL using a view with (model => model.SupplierID, ViewBag.SupplierId as SelectList)

4

1 回答 1

2

我会为此使用jquery。将所选名称添加到您的模型并将其分配给隐藏字段

@Html.HiddenFor(x => x.SelectedName, new { @class = "SelectedName" })

然后在你的脚本中

$('#SupplierID").on('change', function(){
    $('.SelectedName').val($('#SupplierID :selected').text());
});

因此,每次您更改下拉列表时,选定的名称都会被放入隐藏字段中,并将与下拉列表中的选定 ID 一起传递回控制器。希望这会有所帮助

于 2013-11-14T17:52:37.317 回答