I have two models and I want to insert a row in the database with a foreign key relationship populated in the DropDownList. The Item model's data insert without problems but ManufacturerID does not get inserted (it inserts null). I could not find why. Update: Uploaded the project to: http://mvcapplication2.codeplex.com/
<div class="editor-label">
@Html.LabelFor(model => model.ManufacturerID,"Manufacturer")
</div>
<div class="editor-field">
@Html.DropDownList("ManufacturerID",string.Empty)
@Html.ValidationMessageFor(model => model.ManufacturerID)
</div>
public class Item
{
public int ItemID { get; set; }
public string Serial { get; set; }
public string ItemName { get; set; }
public int? ManufacturerID { get; set; }
public Manufacturer Manufacturer { get; set; }
}
public class Manufacturer
{
public int ManufacturerID { get; set; }
public string ManufacturerName { get; set; }
public List<Item> Items { get; set; }
}
public ActionResult Create()
{
ViewBag.ManufacturerID = new SelectList(db.Manufacturers, "ManufacturerID", "ManufacturerName");
return View();
}
[HttpPost]
public ActionResult Create(Item ıtem)
{
if (ModelState.IsValid)
{
db.Items.Add(ıtem);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(ıtem);
}
exception?ManufacturerID(according to your example posted above) comes from theItemclass and is of typeint. Thus it can not be null. Where are you seeing thatManufacturerIDis null? In the controller? In the view? In the database only?