【问题标题】:How to get subcollections on viewmodel on postback in MVC3?如何在 MVC3 的回发中获取视图模型的子集合?
【发布时间】:2011-11-03 12:53:22
【问题描述】:

Phil Haack 有一篇文章描述了如何设置,以便默认模型绑定器在回发时绑定到集合:

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

我遇到的问题是我不只是试图将集合发送回控制器操作,而是一个带有集合的 ViewModel。

我有一个基本上看起来像这样的类:

public class MyViewModel
{
public int IncidentNumber { get; set; }
public string StoreId { get; set; }
public string RepId { get; set; }
public string OrderStatus { get; set; }
public CustomerViewModel Customer { get; set;
//... other properties and SelectLists for binding

public IEnumerable<OrderItemViewModel> OrderItemViewModels { get; set; }

我实际上可以在回发时取回 CustomerViewModel 数据,但 OrderItemViewModels 列表是空的。我怎样才能把那些拿回来?菲尔的文章对此没有帮助。

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-3 viewmodel


    【解决方案1】:

    我在MVC binding to model with list property ignores other properties 遇到了类似的问题,通过在视图中使用以下代码解决了这个问题

    <div class="editor-field">
    @for (int i = 0; i < Model.MyCollection.Count(); i++)
    {
        @Html.HiddenFor(m => m.MyCollection[i].Id)
        @Html.HiddenFor(m => m.MyCollection[i].ParentId)
        @Html.HiddenFor(m => m.MyCollection[i].Name)
        @Html.TextBoxFor(m => m.MyCollection[i].Value)
    }
    </div>
    

    【讨论】:

    • 我对此表示赞同,因为它本质上是正确的答案。我了解到,归根结底是 HTML Input 元素上的 Name 属性。它必须采用某种格式(如其他线程所示)才能让模型绑定器弄清楚。而且您的特定答案是正确的(我必须处理 DropDown 框并且必须手动覆盖 Name 属性才能使其正常工作)
    • 谢谢!我花了太长时间才找到这个答案,我希望更多的人 +1。
    【解决方案2】:

    使用编辑器模板:

    @model MyViewModel
    @using (Html.BeginForm())
    {
        ... some input fields 
    
        @Html.EditorFor(x => x.OrderItemViewModels)
    
        <input type="submit" value="OK" />
    }
    

    然后在相应的编辑器模板中,该模板将自动为OrderItemViewModels 集合(~/Views/Shared/EditorTemplates/OrderItemViewModels.cshtml)的每个元素呈现:

    @model OrderItemViewModels
    <div>
        @Html.LabelFor(x => x.Prop1)
        @Html.EditorForFor(x => x.Prop1)
    </div>
    <div>
        @Html.LabelFor(x => x.Prop2)
        @Html.EditorForFor(x => x.Prop2)
    </div>
    ...
    

    【讨论】:

    • 达林,这不太行,因为单个项目的命名没有正确构建以使数据绑定到参数。
    猜你喜欢
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多