在剃刀多个复选框(使用的foreach) [英] Multiple checkboxes in razor (using foreach)

查看:94
本文介绍了在剃刀多个复选框(使用的foreach)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我无法找到解决办法。
我使用的剃刀,这是我VieModel类。

I have a problem and I can't find solution. I'm using Razor and it is my VieModel class.

public class GroupToExport
{
    public GroupToExport()
    {
        ToExport = false;
    }

    [DisplayName("Export")]
    public bool ToExport { get; set; }
    public Group Group { get; set; }

}

public class GroupsToExport
{
    public GroupsToExport()
    {
        //refill list
    }

    public List<GroupToExport> ExportingGroups { get; set; }
}

查看:

@using (Html.BeginForm("Export", "ElmahGroup", FormMethod.Post, new { id = "toExportForm" }))
{
//some divs
    <input type="submit" id="js-export-submit" value="Export" />
 @foreach (var item in Model.ExportingGroups)
                {
                    <tr>
                        <td class="js-export-checkbox">
                            @Html.CheckBoxFor(modelItem => item.ToExport)
                        </td>
                    </tr>
                }
//some divs
}

控制器:

public ActionResult Export(GroupsToExport model)
    {
        var groupsToExport = model.ExportingGroups.Where(x => x.ToExport).Select(x => x);
        throw new System.NotImplementedException();
    }

提交ToExport后,控制器,每组总有值假。即使所有组进行检查。

After submit "ToExport", in Controller, every group always has value 'false'. Even if all groups are checked.

有人可以帮我吗?我做错了吗?

Can somebody help me? What I'm doing wrong?

推荐答案

您不能使用的foreach 循环生成控件的集合。该HTML的生成每个复选框(以及相关的隐藏输入)&LT;输入类型=复选框NAME =item.ToExport... /&GT; 。您的模型不包含一个叫做财产项目

You cannot use a foreach loop to generate controls for a collection. The html your generating for each checkbox (and for the associated hidden input) is <input type="checkbox" name="item.ToExport" .../>. Your model does not contain a property which is named item

使用循环

@for(int i = 0; i < Model.ExportingGroups.Count; i++)
{
  <tr>
    <td class="js-export-checkbox">
      @Html.CheckBoxFor(m => m.ExportingGroups[i].ToExport)
    </td>
  </tr>
}

现在,你的HTML将

<input name="ExportingGroups[0].ToExport" .../>
<input name="ExportingGroups[1].ToExport" .../>

等。这将正确地绑定到你的模型

etc. which will correctly bind to your model

修改

另外,您可以使用自定义的 EditorTemplate 为typeof运算 GroupToExport 。创建一个局部视图 /Views/Shared/EditorTemplates/GroupToExport.cshtml

Alternatively you can use a custom EditorTemplate for typeof GroupToExport. Create a partial view /Views/Shared/EditorTemplates/GroupToExport.cshtml

@model yourAssembly.GroupToExport
<tr>
  <td class="js-export-checkbox">
    @Html.CheckBoxFor(m => m.ToExport)
  </td>
</tr>

,然后在主视图

@Html.EditorFor(m => m.ExportingGroups)

EditorFor()方法生成基于模板的集合中的每一项正确的HTML。

The EditorFor() method will generate the correct html for each item in your collection based on the template.

这篇关于在剃刀多个复选框(使用的foreach)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆