开发者

ViewModel with IEnumerable<child> member not bound correctly on POST [duplicate]

This question already has answers here: ViewModel's list is null in action (2 answers) Post an HTML Table to ADO.NET DataTable (2 answers) Closed 6 years ago.

I have a view model which contains an IEnumerable of a child view model. When I create an edit form for the parent and children, then post it, only the parent part of the view model is populated; the IEnumerable property remains null.

The view models:

public class FamilyViewModel 
{

    public int idFami开发者_如何学运维ly { 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);
}

Edit.cshtml:

@model FamilyViewModel

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

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

@Html.Submit()
}

The form is generated correctly. If I recast the Edit method to use a FormCollection, the values for both Family and each Member are received correctly. However, I'd prefer to use the strongly-typed ViewModel.

One possibly relevant piece of info: each child form control has the same ID ; that is, there are <INPUT TYPE="text" ID="m_FirstName"> for every MemberViewModel -- they aren't indexed in any way, which I would have expected.


I asked a similar question. I put the solution I used in the body of my question. I believe it might be helpful to you as well. By eliminating that foreach the view elements end up being about to be bound back to the underlying viewmodel. Hope that is helpful to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜