选择要在MVC4中编辑的多个表行

时间:2013-08-14 16:09:33

标签: c# sql forms asp.net-mvc-4 razor

所以我正在用MVC4创建一个网站。基本上我拥有的是许可证表,其中包含许多属性。我希望能够在此表中添加复选框,以便在您选择一组许可证并单击“提交”按钮时,它将允许您批量编辑所选许可证的选定几个属性(例如,它们上的已发布日期) 。我似乎无法找到一种简单的方法来实现它。

1 个答案:

答案 0 :(得分:1)

我不确定是否有 easy 方法来执行此操作。但是,我会提出一个解决方案。 步骤是:

  1. 将一个许可列表发送到视图中有一个操作
  2. 视图在表格中显示它们并让我们使用编辑
  3. 视图发布此列表到另一个操作
  4. 此操作会收到所有许可,编辑或不编辑
  5. 所以,让我们深入研究它。

    型号

    public class License
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Notes { get; set; }
    }
    

    第一次行动

    public ActionResult Index()
    {
        List<License> viewModel = new List<License>();
        viewModel.Add(new License() { Id = 1, Name = "Whatever" });
        viewModel.Add(new License() { Id = 2, Name = "Whatever else" });
        viewModel.Add(new License() { Id = 3, Name = "Nevermind this one" });
    
        return View(viewModel);
    }
    

    查看

    @using (Html.BeginForm("Save", "Home"))
    {
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Notes</th>
                    <th>Edit</th>
                </tr>
            </thead>
            <tbody>
                @{
                    int i = 0;   
                    foreach (MVC4.Test.Models.License l in Model)
                    {
                        <tr>
                            <td><input type="text" name="licenses[@i].Id" readonly value="@l.Id"/></td>
                            <td><input type="text" name="licenses[@i].Name" readonly value="@l.Name" class="_mayEdit" /></td>
                            <td><input type="text" name="licenses[@i].Notes" readonly value="@l.Notes" class="_mayEdit"/></td>
                            <td><input type="checkbox" class="_edit" /></td>
                        </tr>
                        i++;
                    }
                }
            </tbody>
        </table>
        <input type="submit" value="Save" />
    }
    
    <script type="text/javascript">
        $(function () {
            $('._edit').click(function () {
                if ($(this).is(':checked'))
                    $(this).parent().parents('tr').find('._mayEdit').removeAttr('readonly');
                else
                    $(this).parent().parents('tr').find('._mayEdit').attr('readonly', 'readonly');
            });
        });
    </script>
    

    第二次行动

    [HttpPost]
    public ActionResult Save(License[] licenses)
    {
        return View();
    }
    

    有几点需要注意:

    1. 我正在使用 jQuery
    2. 创建输入时请注意该索引。它必须从0开始并递增1.这是模型绑定理解这是项集合的唯一方法
    3. 在第二个动作中,您可以操纵该列表。将其保存到数据库或其他任何内容。