c# - 获取父模型 HttpPost 更新的子集合

标签 c# asp.net-mvc razor

这个问题可能是对上一个问题的重复,如果是,请发布链接。无论哪种方式,我仍然会完成这篇文章。

我有这个模型:

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/

相关文章:

c# - C#-如何按日期对数据表进行排序

javascript - 下拉列表未使用 ajax 和 Controller 操作填充

css - 无法在 Bootstrap 中对齐详细信息页面的静态字段

javascript - 如何使用元素的类正确计算 html 表格列的选中复选框?

c# - jQuery Mobile Datebox 不会采用默认日期值 - 尝试了所有方法

html - MVC 4 : How to convert string into IView?

c# - SQL异常截断字符串或​​二进制数据的奇怪问题

c# - WebBrowser.url 在 winform 中有时不工作

C# 根据多个条件过滤列表中的项目

asp.net-mvc - 在 MVC Razor View 中使用旧版 ASP.NET ASCX 用户控件