I am attempting to populate my database using a create action method. Two fields on my form are dropdownfor menus. The dropdowns are linked to two separate child tables that will ultimately post on my main parent table, via the create method. I am having a very difficult time getting these dropdowns to populate the correct data.
My Model:
public class County
{
[Key]
public string CountyName { get; set; }
}
public class Contact
{
[Key]
public int ContactId { get; set; }
public string ContactName { get; set; }
public class InspectionInfo
{
[Key]
public int InspectionId { get; set; }
//[Required]
public Contact Contact { get; set; }
//[Required]
public County County { get; set; }
My Controller:
//
// GET: /Inspection1/Create
public ActionResult Create()
{
var model = new InspectionInfo
{
Submitted = DateTime.Now,
//Contact = new Contact()
};
ViewBag.CountyName = new SelectList(db.Counties,"CountyName", "CountyName");
ViewBag.Contactname = new SelectList(db.Contacts, "ContactName", "ContactName");
return View(model);
}
//
// POST: /Inspection1/Create
[HttpPost]
public ActionResult Create(InspectionInfo inspectioninfo)
{
if (ModelState.IsValid)
{
db.InspectionInfos.Add(inspectioninfo);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(inspectioninfo);
}
My View:
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.County )
</div>
<div class="editor-field">
@Html.DropDownListFor(m=>m.County.CountyName,(IEnumerable<SelectListItem>)ViewBag.CountyName)
@Html.ValidationMessageFor(model => model.County)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Contact)
</div>
<div class="editor-field">
@Html.DropDownListFor(m=>m.Contact.ContactName, (IEnumerable<SelectListItem>)ViewBag.ContactName)
@Html.ValidationMessageFor(model => model.Contact)
</div>
Currently, I continue to recieve a "1" for ContactName when checking the fields value during break.
Also, I recieve an exception for CountyName:
{"Violation of PRIMARY KEY constraint 'PK_dbo.Counties'. Cannot insert duplicate key in object 'dbo.Counties'.\r\nThe statement has been terminated."}
ANY help here would be greatly appreciated.