动态添加复选框,而不是模型绑定到IList

时间:2013-08-05 23:44:03

标签: javascript jquery asp.net-mvc-4 checkbox model-binding

我有一个视图,为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”字段,则模型绑定器仍然会以RequiresCommentfalse出现。

在每个人都引用Phil Haack's famous collection model binding post之前或者指出我在谈论模型绑定动态生成的HTML元素的其他问题时,让我说我已经成功地使用其他类型的<input />元素做了几次。这只是checkbox似乎不起作用。我已经尝试在元素中添加一个ID,因为Fiddler为从第一个视图调用加载的每个已发布字段添加了<input type="hidden" name="[index].RequiresComment" value="false" />,但我无法获得实际检查到的新行通过true到模型绑定器。我做错了什么?

1 个答案:

答案 0 :(得分:1)

您生成的复选框缺少value参数,在您的情况下应将其设置为true

据我记忆,提交时只提交选中的复选框值。因此,MVC始终创建一个隐藏字段以确保未经检查的复选框的值始终提交。虽然复选框通常用于布尔值,但该值也可以是文本或数字。

相关问题