0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I think the cast to SelectList isn't necessary at all. ViewBag.CountyName is a SelectList anyway. And the two Attach calls must be before the Add.
Hey Daniel thanks for the reply I really appreciate the effort. I am making headway with this. I'm wondering though... is it even possible to have a dropdownfor with a table that only has one column...? Ideally I would like to have CountyName be the only column in that particular table, as the name is unique enough to not require an ID. Doesn't seem to work without one though.
You can give a shot to [this ](stackoverflow.com/questions/10604471/…). Check out @Terry's answer.
Thanks for the help Daniel, discovered another solution to this, will post soon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.