I have a db with two tables Invoices and Customers. Customers PK is FK in the Invoices table. I have a Create view in which user fills in invoice data. On this form I have a @Html.DropDownList with SelectList populated with the names of already existing in the db customers. On the basis of user selection customer data fields are autopopulated with customer data from the database via partial view:
@using (Ajax.BeginForm("CustomerSelect", "Invoice", new AjaxOptions{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "CustomerFields"}))
This works well, but when I create the Submit button, it creates a new instance of the cutomer in the database, even though it should use the id of one retrieved from the db. When the partial view is displayed on the Create view it displayes proper Customer ID:
<div class="editor-label">
@Html.LabelFor(model => model.Customer)
<div class="editor-field">
@Html.EditorFor(model => model.Customer)
@Html.ValidationMessageFor(model => model.Customer)
</div>
</div>
But when I look inside the invoice object in the httppost of controler Create method it shows shows a different (new) Customer ID:
[HttpPost]
public ActionResult Create(Invoice invoice)
{
if (ModelState.IsValid)
{
db.Invoices.Add(invoice); **//invoice.Customer.CustomerID == 1**
db.SaveChanges(); **//invoice.Customer.CustomerID changes to next free in the db == 7**
return RedirectToAction("Index");
}
return View(invoice);
}
What am I doing wrong?