我正在开发我的第一个 ASP.NET MVC 3 应用程序,我有一个如下所示的视图:
@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 在传递到视图时填充得很好。但是,当单击提交按钮时,处理帖子的控制器操作仅具有视图模型的 Name 属性的值。 Notes 属性(用户已选中/取消选中的注释列表)为空。当显示视图时,这些 TextBoxFor 和 CheckBoxFor 元素的填充与发送回的 ViewModel 之间存在脱节。对此有何指导?
SOLUTION感谢神秘人让我明白了这一点。据我了解,本质上是通过将循环更改为
@Html.EditorFor(m => m.Notes)
更改底层 HTML,据我所知,它提供了帖子上正确的模型绑定。查看生成的 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 本质上会丢失对视图模型的注释属性的任何引用,并且虽然 HTML 被正确填充,但复选框值的设置无法将其值传递回视图模型,我想这就是重点模型绑定。
所以我学到了一些东西,这很好。