【问题标题】:Getting the Child Collection for Parent Model HttpPost Update获取父模型 HttpPost 更新的子集合
【发布时间】:2012-09-08 01:23:28
【问题描述】:

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

我有这个模型:

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
}

我正在使用此操作在我的视图上显示:

[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);
    }
}

这是我的观点:

@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 在视图上显示子集合,并为每个集合使用部分视图。

当调用我的 Post Edit Action 时,employee 模型将子集合设置为 null。

[HttpPost]
public ActionResult Edit(Employee employee) {
    using(var context = new EPMSContext()) {

    }

    return View();
}

为了让子集合正确,我缺少什么?

谢谢!

【问题讨论】:

  • 您能说明您使用什么代码来发起 POST 请求吗?还显示一个示例 HTTP POST 请求也会有所帮助,即您要发布什么数据?听起来 ASP.NET 无法反序列化集合,因此它有助于查看您尝试发送的数据。
  • 我已经更新了我的问题,希望您的建议正确。
  • 另外,我检查了 Request.Form 对象,发现集合在请求中。如何让我的子集合包含在我传递的 Employee 对象中?

标签: c# asp.net-mvc razor


【解决方案1】:

我认为问题与 MVC 期望构建集合元素的方式有关(它们在 html 中的名称)。 看看这个 SO 答案:https://stackoverflow.com/a/6212877/1373170,尤其是 Scott Hanselman 的post 的链接。

您的问题在于,如果您手动迭代并执行单独的RenderPartial() 调用,输入字段将没有索引,DefaultModelBinder 将不知道如何构造您的集合。

我会亲自为您的两种 ViewModel 类型创建 Editor Templates,并使用 @Html.EditorFor(model =&gt; model.EducationalHistories)@Html.EditorFor(model =&gt; model.ProfessionalExperiences)

【讨论】:

  • 好的,我已经制作了我的编辑器模板。我使用了一个 foreach 来遍历子集合列表。我做对了吗?
  • 您根本不需要 foreach。让 MVC 处理迭代并为它解决正确的模板。
  • 我确实尝试使用包含在 IEnumerable 中的类作为编辑器模板(即使在显示模板中我的意思)但是有一个错误说我正在尝试将集合传递给仅处理类的视图。我忘了提到我的孩子收藏设置为虚拟。我应该删除它以仅对父实体的那些成员禁用延迟加载吗?
  • 奇怪。你如何调用 EditorFor 或 DisplayFor?
  • 现在可以使用了。我使用了this 助手,我什至清理了我的模型的导航属性以确保我不必关闭延迟加载...
猜你喜欢
  • 1970-01-01
  • 2023-02-01
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 2012-01-21
相关资源
最近更新 更多