【问题标题】:ViewModel with IEnumerable<child> member not bound correctly on POST [duplicate]带有 IEnumerable<child> 成员的 ViewModel 在 POST 上未正确绑定 [重复]
【发布时间】:2011-08-29 00:41:25
【问题描述】:

我有一个包含子视图模型的 IEnumerable 的视图模型。当我为父级和子级创建一个编辑表单,然后发布它时,只有视图模型的父级部分被填充; IEnumerable 属性保持为空。

视图模型:

public class FamilyViewModel 
{

    public int idFamily { get; set; }
    public string FamilyName { get; set; }
public IEnumerable<MemberViewModel> Members { get; set; }

}

public class MemberViewModel 
{

    public int idMember { get; set; }
    public int idFamily { get; set; }
    public string FirstName { get; set; }
}

FamilyController.cs

 [HttpGet]
public ActionResult Edit(int id)
{
    var family = unitOfWork.FamilyRepository.Single(f => f.idFamily == id);
    FamilyViewModel viewModel = Mapper.Map<family, FamilyViewModel>(family);
            /* at this point, viewModel.Members is populated correctly */
    return View(viewModel);
}

[HttpPost]
public ActionResult Edit(FamilyViewModel viewModel)
{
    /* at this point, viewModel.Members is null */
    return View(viewModel);
}

编辑.cshtml:

@model FamilyViewModel

@using (Html.BeginForm())
{
@Html.EditorFor(s => Model, "Family")

@foreach (MemberProfileViewModel m in Model.Members)
{
   @Html.EditorFor(o => m, "Member")
}

@Html.Submit()
}

表单已正确生成。如果我重铸 Edit 方法以使用 FormCollection,则家庭和每个成员的值都会正确接收。不过,我更喜欢使用强类型的 ViewModel。

一条可能相关的信息:每个子表单控件都有相同的 ID;也就是说,每个 MemberViewModel 都有&lt;INPUT TYPE="text" ID="m_FirstName"&gt;——它们没有以任何方式编入索引,这是我所预料的。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    I asked a similar question。我将我使用的解决方案放在我的问题正文中。我相信它也可能对你有帮助。通过消除foreach,视图元素最终将被绑定回底层视图模型。希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 2015-03-09
      • 2015-09-04
      • 1970-01-01
      • 2013-08-11
      相关资源
      最近更新 更多