这个问题可能是对上一个问题的重复,如果是,请发布链接。无论哪种方式,我仍然会完成这篇文章。
我有这个模型:
public class Employee {
//omitted for brevity
public virtual ICollection<ProfessionalExperience> ProfessionalExperiences { get; set; }
public virtual ICollection<EducationalHistory> EducationalHistories { get; set; }
}
public class ProfessionalExperience {
// omitted for brevity
}
public class EducationalHistory {
// omitted for brevity
}
我正在通过此操作在我的 View 中显示:
[HttpGet]
public ActionResult Edit(int id) {
using(var context = new EPMSContext()) {
var employees = context.Employees.Include("ProfessionalExperiences").Include("EducationalHistories");
var employee = (from item in employees
where item.EmployeeId == id && item.IsDeleted == false
select item).FirstOrDefault();
return View(employee);
}
}
Here is my View:
@using(Html.BeginForm()) { <div class="editor-label">First Name:</div> <div class="editor-field">@Html.TextBoxFor(x => x.FirstName)</div> <div class="editor-label">Middle Name:</div> <div class="editor-field">@Html.TextBoxFor(x => x.MiddleName)</div> @foreach(var item in Model.ProfessionalExperiences) { Html.RenderPartial("ProfExpPartial", item); } @foreach(var item in Model.EducationalHistories) { Html.RenderPartial("EducHistPartial", item); } <input type="submit" value="Save" /> }
我使用 foreach
在 View 上显示子集合,并对每个集合使用局部 View 。
当调用我的 Post Edit Action 时,employee
模型将子集合设置为 null。
[HttpPost]
public ActionResult Edit(Employee employee) {
using(var context = new EPMSContext()) {
}
return View();
}
我缺少什么才能正确获取子集合?
谢谢!
最佳答案
我认为问题与 MVC 期望构建集合元素的方式有关(它们在 html 中的名称)。 看看这个 SO 答案:https://stackoverflow.com/a/6212877/1373170 ,尤其是指向 Scott Hanselman 的 post 的链接.
您的问题在于,如果您手动迭代并执行单个 RenderPartial()
调用,输入字段将没有索引,并且 DefaultModelBinder
将不知道如何构建您的集合。
我会亲自创建 Editor Templates对于您的两种 ViewModel 类型,并使用 @Html.EditorFor(model => model.EducationalHistories)
和 @Html.EditorFor(model => model.ProfessionalExperiences)
.
关于c# - 获取父模型 HttpPost 更新的子集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12327291/