I am trying to get a dropdown list to send back it's selection on HTTP POST along with the other related data. I can see the value inside a Form Collection, but I VS2010 tells me that the object is NULL when I look at the other posted entities.
This model has a many to one relationship:
[Key]
public int ProgramTypeId { get; set; }
public string ProgramType { get; set; }
public List<SurveyProgramModels> SurveyProgramModel { get; set; }
This model uses the ProgramTypeId as a foreign key
public class SurveyProgramModels
{
[Key]
public Guid ProgramId { get; set; }
public virtual SurveyProgramTypeModels SurveyProgramTypeModels { get; set; }
public int ProgramYear { get; set; }
public int ProgramStatus { get; set; }
}
Controller GET/POST
//
// GET: /SurveyProgram/Create
public ActionResult Create()
{
SelectList typelist = new SelectList(db.SurveyProgramTypeModels.ToList(), "ProgramTypeId", "ProgramType", db.SurveyProgramTypeModels);
ViewData["SurveyProgramTypeModels"] = typelist;
return View();
}
//
// POST: /SurveyProgram/Create
[HttpPost]
public ActionResult Create(SurveyProgramModels surveyprogram, FormCollection collection)
{
SelectList typelist = new SelectList(db.SurveyProgramTypeModels.ToList(), "ProgramTypeId", "ProgramType", db.SurveyProgramTypeModels);
ViewData["SurveyProgramTypeModels"] = typelist;
// int SelectedCollection = Int32.Parse(collection["ProgramTypeId"]);
if (ModelState.IsValid)
{
surveyprogram.ProgramId = Guid.NewGuid();
db.SurveyPrograms.Add(surveyprogram);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(surveyprogram);
}
Select list in the view:
<div class="editor-field">
@Html.DropDownList("ProgramTypeTypeModels", (IEnumerable<SelectListItem>)ViewData["SurveyProgramTypeModels"])
@Html.ValidationMessageFor(model => model.SurveyProgramTypeModels)
</div>
The Select list is correct when rendered in the view, and I can see the selected value as a part of the form collection. I'm not sure why the selected value isn't being saved along with the other data for SurveyProgramModels.
Edit: I should also mention the data submits correctly when I remove the relationship between the two classes.