说我有这样的看法:
<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">×</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。
答案 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);
}
}
Here是另一种方式。