如何使用复选框进行批处理操作?

时间:2018-09-12 21:53:26

标签: asp.net-mvc-5 bootstrap-modal

说我有这样的看法:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#assign">
    Assign
</button>
<table class="table table-hover table-bordered table-sm">
    <thead class="thead-light">
        <tr>
            <th></th>
            <th>Name</th>
        </tr>
    </thead>
    @foreach (var employee in ViewBag.employees)
    {
        <tr>
            <td><input type="checkbox" name="@employee.Id" /></td>
            <td>@employee.Name</td>
        </tr>
    }
</table>
<!-- Modal -->
<div class="modal fade" id="assign" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">Assign employee to group</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- a dropdown of groups -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary">Assign</button>
            </div>
        </div>
    </div>
</div>

我有一个控制器要呼叫:

public ActionResult Assign(List<int> employeeIds, int groupId)

如何从模态下拉列表中获取已检查的Id列表和groupId,以便可以调用控制器?

例如,如果数据看起来像这样

0. Alice
1. Bob
2. Charlie
3. Dan

我检查了Bob和Charlie并想将它们分配给组1,所以employeeId将是1和2,而groupId将是1。

1 个答案:

答案 0 :(得分:0)

您需要使用for循环而不是foreach。此外,我建议使用ViewModel代替ViewBag

@using (Html.BeginForm("Index", "Home", FormMethod.Post, null))
{
    for (int i = 0; i < Model.Employees.Count; i++)
    {
        <tr>
            <td>@Html.CheckBoxFor(x => Model.Employees[i].Checked)</td>
            <td>@Model.Employees[i].Name</td>
        </tr>
    }
    <input type="submit" value="Submit" />
}

型号

您想重命名ViewModel有意义的内容。

public class ViewModel
{
    public List<Employee> Employees { get; set; }
    public int GroupId { get; set; }
}

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Checked { get; set; }
}

控制器

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewModel vm = new ViewModel
        {
            Employees = new List<Employee>
            {
                new Employee {Id=1, Name = "John", Checked = true},
                new Employee {Id=2, Name = "Eric", Checked = false}
            }
        };
        return View(vm);
    }

    [HttpPost]
    public ActionResult Index(ViewModel vm)
    {
        return View(vm);
    }
}

enter image description here

enter image description here

Here是另一种方式。