如何将IEnumerable列表传递到MVC中的控制器(包括复选框状态)?

我有一个mvc应用程序,其中使用了这样的模型:


 public class BlockedIPViewModel

{

    public string  IP { get; set; }

    public int ID { get; set; }

    public bool Checked { get; set; }

}

现在我有一个视图来绑定这样的列表:


@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>

现在,我有一个控制器可以从“提交”按钮接收操作:


 public ActionResult BlockedIPList(IEnumerable<BlockedIPViewModel> lstBlockedIPs)

 {


  }

但是当我进入控制器动作时,我得到的lstBlockedIPs为空值。我需要在这里获取复选框状态。请帮忙。


临摹微笑
浏览 703回答 2
2回答

呼啦一阵风

请改用列表,然后将foreach循环替换为for循环:@model IList<BlockedIPViewModel>@using (Html.BeginForm())&nbsp;{&nbsp;&nbsp; &nbsp; @Html.AntiForgeryToken()&nbsp; &nbsp; @for (var i = 0; i < Model.Count; i++)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Html.HiddenFor(x => x[i].IP)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Html.CheckBoxFor(x => x[i].Checked)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Html.DisplayFor(x => x[i].IP)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </td>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; }&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <input type="submit" value="Unblock IPs" />&nbsp; &nbsp; </div>}或者,您可以使用编辑器模板:@model IEnumerable<BlockedIPViewModel>@using (Html.BeginForm())&nbsp;{&nbsp;&nbsp; &nbsp; @Html.AntiForgeryToken()&nbsp; &nbsp; @Html.EditorForModel()&nbsp; &nbsp;&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <input type="submit" value="Unblock IPs" />&nbsp; &nbsp; </div>}然后定义~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml将为集合的每个元素自动呈现的模板:@model BlockedIPViewModel<tr>&nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp; @Html.HiddenFor(x => x.IP)&nbsp; &nbsp; &nbsp; &nbsp; @Html.CheckBoxFor(x => x.Checked)&nbsp; &nbsp; </td>&nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp; @Html.DisplayFor(x => x.IP)&nbsp; &nbsp; </td></tr>您在控制器中获得null的原因是因为您不遵守默认模型绑定程序希望成功绑定到列表的输入字段的命名约定。我邀请你阅读following article。阅读完后,请结合我的示例和您的示例查看生成的HTML(更具体地说是输入字段的名称)。然后进行比较,您将了解为什么您的列表不起作用。
打开App,查看更多内容
随时随地看视频慕课网APP