WiseGuy
WiseGuy

Reputation: 429

Populating DB with child table data via Html Dropdownfor MVC3/ entity framework

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.

Upvotes: 0

Views: 461

Answers (1)

danielQ
danielQ

Reputation: 2086

Well there are two issues. As you said, your dropdown population might be wrong. When you say DropDownListFor, it ask as your fisrt param for a model property, in your case it would be just your County. Secondly, I'm not sure if IEnumerable<SelectListItem>)ViewBag.CountyName works, try (SelectList)ViewBag.CountyName. And, if possible, use your ids as ValueMembers, unless you're really those you use are unique values.

Secondly, when you store the data, you need to attach back both County and Contact entities, otherwise the context will think those are you entities and try to add them, which causes that PRIMARY KEY Violation.


So, let's modify your code like:

Controller:

// Use the entity id here...
ViewBag.CountyName = new SelectList(db.Counties,"CountyId", "CountyName");

Page:

@Html.DropDownListFor(m=>m.County.CountyName,(SelectList)ViewBag.CountyName)

On your controller:

[HttpPost]
    public ActionResult Create(InspectionInfo inspectioninfo)
    {
            if (ModelState.IsValid)
        {
            db.InspectionInfos.Add(inspectioninfo);
            db.Contact.Attach(inspectioninfo.Contact);
            db.County.Attach(inspectioninfo.County);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(inspectioninfo);
    }

Play a little around with this, it should work.

Upvotes: 1

Related Questions