0
我想要得到一个下拉列表来发送它在HTTP POST上的选择以及其他相关数据。我可以看到表单集合中的值,但是当我查看其他发布的实体时,VS2010告诉我该对象为NULL。在模型对象中返回NULL的MVC3下拉列表
这种模式有一个多对一的关系:
[Key]
public int ProgramTypeId { get; set; }
public string ProgramType { get; set; }
public List<SurveyProgramModels> SurveyProgramModel { get; set; }
这款机型采用了ProgramTypeId作为外键
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; }
}
控制器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);
}
选择列表查看:
<div class="editor-field">
@Html.DropDownList("ProgramTypeTypeModels", (IEnumerable<SelectListItem>)ViewData["SurveyProgramTypeModels"])
@Html.ValidationMessageFor(model => model.SurveyProgramTypeModels)
</div>
选择列表在视图中呈现时是正确的,我可以将选定值看作表单集合的一部分。我不确定为什么选定的值未与SurveyProgramModels的其他数据一起保存。
编辑:当我删除两个类之间的关系时,我还应该提及数据提交正确。