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

Pra*_* VR 49 c# asp.net-mvc model-binding razor asp.net-mvc-4

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

 public class BlockedIPViewModel
{
    public string  IP { get; set; }
    public int ID { get; set; }
    public bool Checked { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个View来绑定像这样的列表:

@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>
Run Code Online (Sandbox Code Playgroud)

现在我有一个控制器来接收来自提交按钮的动作:

 public ActionResult BlockedIPList(IEnumerable<BlockedIPViewModel> lstBlockedIPs)
 {

  }
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*rov 93

改为使用列表并用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>
}
Run Code Online (Sandbox Code Playgroud)

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

@model IEnumerable<BlockedIPViewModel>

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

然后定义~/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>
Run Code Online (Sandbox Code Playgroud)

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

阅读完毕后,使用我的示例和您的示例查看生成的HTML(更具体地说,输入字段的名称).然后比较,你会明白为什么你的工作不起作用.

  • 此外,原始源代码中的隐藏字段和复选框不在表单的"using"块中.那可能是个问题. (3认同)