视图模型具有的IEnumerable<儿童>会员未正确绑定在POST [英] ViewModel with IEnumerable<child> member not bound correctly on POST

查看:131
本文介绍了视图模型具有的IEnumerable<儿童>会员未正确绑定在POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一个IEnumerable子视图模型视图模型。当我创建了家长和孩子们的编辑表单,然后发布它,只有视图模型的父部分人口;了IEnumerable属性保持为空。

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.

视图模式:

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

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:

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()
}

的形式正确生成。如果我重铸编辑方法使用的FormCollection,为家庭和各成员国的值被正确接收。不过,我想preFER使用强类型的视图模型。

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.

一个可能相关的一块信息:每个子窗体控件具有相同的ID;也就是说,有&LT; INPUT TYPE =TEXTID =m_FirstName&GT; 每个的MemberViewModel - 他们没有索引以任何方式,我本来期望。

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.

推荐答案

我问了类似的问题。我把我在我的问题的主体中使用的解决方案。我相信这可能是有益的你。通过消除的foreach 视图元素最终会被即将被绑定到底层视图模型。希望对你有帮助。

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.

这篇关于视图模型具有的IEnumerable&LT;儿童&GT;会员未正确绑定在POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆