asp.net - ViewModel 的列表在操作中为 null

标签 asp.net asp.net-mvc asp.net-mvc-3

我正在开发我的第一个 ASP.NET MVC 3 应用程序,我有一个如下所示的 View :

@model IceCream.ViewModels.Note.NotesViewModel
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    @Html.TextBoxFor(m => m.Name)

    foreach (var item in Model.Notes)
    {
        @Html.EditorFor(m => item);
    }

    <input type="submit" value="Submit"/>
}

我有一个如下所示的 EditorTemplate:

@model IceCream.ViewModels.Note.NoteViewModel
<div>
    @Html.HiddenFor(m => m.NoteID)
    @Html.TextBoxFor(m => m.NoteText)
    @Html.CheckBoxFor(m => m.IsChecked)
</div>

NotesViewModel 看起来像这样:

    public class NotesViewModel
    {
        public string Name { get; set; }
        public IEnumerable<NoteViewModel> Notes { get; set; }
    }

NoteViewModel 看起来像这样:

public class NoteViewModel
{
    public int NoteID { get; set; }
    public System.DateTime Timestamp { get; set; }
    public string NoteText { get; set; }
    public bool IsChecked { get; set; }
}

NotesViewModel 在传递到 View 时填充得很好。但是,当单击提交按钮时,处理帖子的 Controller 操作仅具有 View 模型的 Name 属性的值。 Notes 属性(用户已选中/取消选中的注释列表)为空。当显示 View 时,这些 TextBoxFor 和 CheckBoxFor 元素的填充与发送回的 ViewModel 之间存在脱节。对此有何指导?

<小时/>

解决方案 感谢神秘人让我明白了这一点。据我了解,本质上是通过将循环更改为

@Html.EditorFor(m => m.Notes)

更改底层 HTML,据我所知,它提供了帖子上正确的模型绑定(bind)。查看生成的 HTML,我发现为其中一个注释生成了以下内容:

<div>
  <input id="Notes_0__NoteId" type="hidden" value="1" name="Notes[0].NoteId">
  <input id="Notes_0__NoteText" type="text" value="Texture of dessert was good." name="Notes[0].NoteText">
  <input id="Notes_0__IsChecked" type="checkbox" value="true" name="Notes[0].IsChecked>
</div>

这与我的原始代码生成的 HTML 不同:

<div>
   <input id="item_NoteId" type="hidden" value="1" name="item.NoteId>
   <input id="item_NoteText" type="text" value="Texture of dessert was good." name="item.NoteText" >
   <input id="item_IsChecked" type="checkbox" value="true" name="item.IsChecked">
</div>

通过循环注释,生成的 HTML 本质上会丢失对 View 模型的注释属性的任何引用,并且当 HTML 正确填充时,复选框值的设置无法将其值传递回 View 模型,我猜这是是模型绑定(bind)的点。

所以我学到了一些东西,这很好。

最佳答案

你是个聪明人,所以看看你的观点。然后,考虑如何生成 HTML。然后,考虑回发时模型绑定(bind)器应该如何根据生成的 HTML 重新填充 Notes。

我想您会发现您的 HTML 中没有足够的信息供 Model Binder 识别。

考虑一下:

@EditorFor(m => Model.Notes)

而不是 for 循环,在 for 循环中,您基本上从 EditorFor 函数中隐藏了上下文。

关于asp.net - ViewModel 的列表在操作中为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7155747/

相关文章:

javascript - 处理剑道网格中列的模板

c# - 传递到字典中的模型项的类型为 '`,但该字典需要类型为 'System.Collections.Generic.IEnumerable' 的模型项

c# - ASP.NET MVC 5 & Entity Framework 多对多关系

c# - 在 gridview 中隐藏分页号码?

c# - RememberMe 设置如何与 MVC 项目中的 WebSecurity 一起使用?

asp.net-mvc - ASP.NET MVC1如何直接升级到MVC3?

c# - AngularJs $http.post 不渲染新 View

javascript - 如何在jquery自动完成中添加清除按钮(mvc razor)

c# - 按位/ bool 值选择

linq - ASP.NET MVC 2/.NET 4/Razor - 不能在 ViewModel 成员上使用 Any() 扩展方法