编辑包含List <t>的模型的视图,其中T是另一个类</t>

时间:2011-08-19 11:11:14

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

在光天化日之下,我似乎很纠结:

我有一个模型类

public class Pilot
{
    //.. other prop-s escaped
    private List<FlightHoursEntry> FlightHours { get; set; }
}

public class FlightHoursEntry
{
    public string Description { get; set; }

    public int Hours { get; set; }
}

视图列表为bleow,所有内容都正确显示,但回传FlightHours属性上的为空,为什么引擎没有正确初始化Pilot的对象?

PilotEditView中的

我正在使用 @ Html.EditorFor(model =&gt; model.FlightHours)

FlightHoursCollectionView是:

@model List<FlightHoursEntry>

@for (int i = 0; i < Model.Count; i++){
FlightHoursEntry fh = Model[i];
@Html.Partial("~/../FlightHoursEntryEditView.cshtml", fh);}

我也尝试过这种方式     @ Html.EditorFor(model =&gt; model [i],“FlightHoursEntryEditView”,fh)

和简单的FlightHoursEntryEditView

@model PumaMvc.Models.BusinessObjects.Copa.FlightHoursEntry

    <div class="editor-label">
        @Html.LabelFor(model => model.Hours)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Hours)
        @Html.ValidationMessageFor(model => model.Hours)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Description)
    </div>
    <div class="editor-field">      
        @Html.TextAreaFor(model => model.Description)           
        @Html.ValidationMessageFor(model => model.Description)
    </div>

2 个答案:

答案 0 :(得分:0)

该字段标记为private。我怀疑该字段需要公开,以便MVC ModelBinder将传入的值绑定到它。

编辑:

如果上述方法无效:

同时检查一下:http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx Phil博客关于如何将模型绑定到复杂对象列表,您需要更改FlightHoursEntry类的编辑器以反映它在那里显示的内容。只需在最终HTML中的方括号内呈现i的值。

那里还有一个例子,但帖子有点过时了,MVC2随处可见。

答案 1 :(得分:0)

查看以下帖子。真正帮助我了解如何实现这一点 - Return a List<E> from a view in view model