2

誰でもこれを行う方法を手伝ってもらえますか?

私はモデルを持っています

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

を使用して、製品のと の@Html.DropDownListFor両方に入力したいSupplierIDSupplier

私が使用する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);
}

( model => model.SupplierID, ViewBag.SupplierId as SelectList) でビューを使用しているdb.SaveChangesと不平を言いますSupplierNULL

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 に答える