我正在尝试获取一个下拉列表,以将其在 HTTP POST 上的选择连同其他相关数据一起发回。我可以看到表单集合中的值,但是当我查看其他发布的实体时,VS2010 告诉我该对象为 NULL。
该模型具有多对一关系:
[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 的其他数据一起保存。
编辑:当我删除两个类之间的关系时,我还应该提到正确提交的数据。