【问题标题】:Edit View for the model that contains the List <T> where T some another class包含 List <T> 的模型的编辑视图,其中 T 是另一个类
【发布时间】:2023-03-30 02:04:02
【问题描述】:

我好像在光天化日之下纠结:

我有一个模型类

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; }
}

Views 被列出来,所有的显示都正确,但是在回发 FlightHours 属性是 null,为什么引擎没有正确初始化 Pilot 的对象?

在 PilotEditView 我正在使用 @Html.EditorFor(model => 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=>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>

【问题讨论】:

  • 你不需要Html.Partial(..之前的第二个代码段中的@符号,因为你已经在C#上下文中了

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


【解决方案1】:

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

编辑:

如果上述方法不起作用:

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

那里也有一个例子,但是帖子有点过时了,而且到处都在使用 MVC2。

【讨论】:

  • 如果访问修饰符 private 是原因,请告诉我,谢谢。
  • 不,在实际代码中它是公共财产,仅在帖子中出错。感谢您阅读这篇文章。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2016-07-06
    相关资源
    最近更新 更多