user2903089
user2903089

Reputation: 313

@Html.DropDownListFor get ID and value into model along with differing names for ID

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)

Upvotes: 2

Views: 2358

Answers (1)

Matt Bodily
Matt Bodily

Reputation: 6423

I would use jquery for this. Add selected name to your model and assign it to a hidden field

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

then in your script

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

So every time you change the drop down the selected name gets put in the hidden field and that will get passed back to the controller along with the selected id from the dropdown. Hopefully this helps

Upvotes: 2

Related Questions