53

I have an mvc application in which I am using a model like this:

 public class BlockedIPViewModel
{
    public string  IP { get; set; }
    public int ID { get; set; }
    public bool Checked { get; set; }
}

Now I have a View to bind a list like this:

@model IEnumerable<OnlineLotto.Web.Models.BlockedIPViewModel>
@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()
}

@foreach (var item in Model) {
<tr>
    <td>

        @Html.HiddenFor(x => item.IP)           
        @Html.CheckBoxFor(x => item.Checked)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.IP)
    </td>

</tr>
}

<div>
    <input type="submit" value="Unblock IPs" />
</div>

Now I have a controller to receive action from submit button:

 public ActionResult BlockedIPList(IEnumerable<BlockedIPViewModel> lstBlockedIPs)
 {

  }

But I am getting null value to lstBlockedIPs when coming to controller action.I need to get the checkbox state here. Please help.

4

1 回答 1

96

改用列表并用foreach循环替换for循环:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

或者,您可以使用编辑器模板:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

然后定义~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml将为集合的每个元素自动呈现的模板:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

您在控制器中获得 null 的原因是您不遵守默认模型绑定器期望成功绑定到列表的输入字段的命名约定。我邀请你阅读following article

阅读完后,请查看生成的 HTML(更具体地说,是输入字段的名称)以及我的示例和您的示例。然后比较一下,你就会明白为什么你的不起作用了。

于 2013-06-11T06:39:35.743 回答