我有一个视图,它为 an 吐出一个表,IList<T>
如下T
所示:
public class ModelType
{
public int EntityId { get; set; }
public string Description { get; set; }
public bool RequiresComment { get; set; }
}
Razor 代码(为简洁起见被截断):
@model IList<ModelType>
<table id="theTable">
<thead>
<tr>
<th>Description</th>
<th>Requires Comment</th>
</tr>
</thead>
<tbody>
@for(var i = 0;i < Model.Count;i++)
{
<tr>
@Html.HiddenFor(m => m[i].EntityId)
<td>
@Html.TextBoxFor(m => m[i].Description)
</td>
<td>
@Html.CheckBoxFor(m => m[i].RequiresComment)
</td>
</tr>
}
</tbody>
</table>
<input type="button" id="addRowButton" value="Add Row" />
<input type="submit" value="Save" />
然后,我有一些 jQuery 来处理“添加行”单击事件:
$("#addRowButton").click(function(){
var index = $("#theTable tbody tr").length;
var newRow = '<tr><input type="hidden" name="[' + index + '].EntityId" value="0" />' +
'<td><input type="text" name="[' + index + '].Description" style="width: 98%" /></td>' +
'<td style="text-align: center;"><input type="checkbox" name="[' + index + '].RequiresComment" />' +
'<input name="[' + index + '].RequiresComment" type="hidden" value="false" /></td></tr>';
$("#theTable tbody tr:last").after(newRow);
});
表格行被完美地添加,当我摆弄 POST 时,一切看起来都很好(据我所知)。但是由于某种原因,如果添加了新行并且在新添加的行上检查了“RequiresComment”字段,则模型绑定器的RequiresComment
值仍然为false
.
在大家参考Phil Haack 著名的集合模型绑定帖子或向我指出其他关于模型绑定动态生成的 HTML 元素的问题之前,让我说我已经用其他类型的<input />
元素成功地完成了几次。这只是checkbox
似乎不起作用。我尝试向元素添加一个 ID,<input type="hidden" name="[index].RequiresComment" value="false" />
为从第一个视图调用加载的每个已发布字段添加一个 as Fiddler 显示,但我无法获得实际检查通过的新true
行模型粘合剂。我究竟做错了什么?