c# - 如何将数据从复选框 (html) 导入数据库 ASP.NET Core MVC
问题描述
我有一个客人列表,存储在我的数据库中。创建聚会后,我希望用户能够邀请客人参加聚会。
为此,我有两个具有一对多关系的表。在第一个表(客人)中,我有客人的信息,在第二个表(PartyGuests)中,还有另外两列用于引用其他内容。
用户创建聚会后,将出现一个客人列表,用户可以在其中通过选中复选框来选择他想邀请的任何人。单击提交按钮将所有选定的客人 ID 传递给控制器。
这是我的观点。
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Operation</th>
</tr>
</thead>
<tbody>
@foreach (var item in ViewBag.Guests)
{
<tr>
<td>@item.FirstName</td>
<td>@item.LastName</td>
<td><input type="checkbox" name="guests" value="@item.Id"></td>
</tr>
}
</tbody>
</table>
<input type="hidden" value="@Model.Id" name="eventId"/>
<button type="submit" class="btn btn-primary">Invite</button>
</form>
这是我的控制器:
[HttpGet]
public IActionResult Invite(int id)
{
ViewBag.Guests= _guestService.GetGuests(); //Display list of guests for invitation
ViewBag.Id = id;
return View(_eventService.GetEvent(id)); // Return event to get the event information o the Invite page
}
[HttpPost]
public IActionResult Invite(int eventId, string[] guests)
{
foreach (var item in guests)
{
var newGuest = new EventGuest
{
EventId = eventId,
GuestId = int.Parse(item)
};
// LINQ -- To avoid invite a guest more than once
if (_eventService.IsInvited(newGuest.GuestId, eventId)) // Does not invite
{
return RedirectToAction("Error", "Something"); // Give an error message
}
else
{
_eventService.InviteGuest(newGuest);
_eventService.SaveChanges();
}
}
return View("Index", "Home");
}
现在,问题是我希望在他们已经被邀请时检查被邀请的客人复选框。换句话说,如果派对经理想要添加更多,他可以通过查看选中的复选框来识别被邀请的客人。
我应该注意,我的数据库通过此操作在其列中获取有效数据
我不熟悉 JavaScript,所以请帮助我处理 HTML。
谢谢
解决方案
首先要注意的是,您在操作中有一个用于客人的字符串数组,但我怀疑这应该是一个整数数组。您还可以有一个通用的整数列表,它也应该可以工作。
以下内容对我有用 - 请注意,如果未选中任何复选框,则 ID 列表为空
<form method="post" asp-area="YourArea" asp-controller="YourController" asp-action="Test">
<button type="submit">Post</button>
<input type="hidden" value="123" name="eventId" />
@for (int index = 0; index < Model.Count; index++)
{
<input type="checkbox" name="checkedIdList" value="@Model[index].Id" />
}
</form>
[HttpPost]
public async Task<IActionResult> Test(int eventId, List<int> checkedIdList)
{
await Task.CompletedTask;
return RedirectToAction("Index");
}
推荐阅读
- node.js - 纱线安装失败导入系统;打印 "%s.%s.%s" % sys.version_info[:3] 无效语法
- vba - 如何根据 VBA 中的另一个组合框值更改组合框的可见性
- python - Spacy:当被不同名称引用时,计算实体的频率
- windows - 无法在 Windows 中安装 pulsar-client
- excel - Excel 保留原始数据集格式
- tensorflow - 将 tf/Keras 模型转换为 pytorch 时出现问题?
- azure-ad-b2c - AD B2C 认证用户
- html - 四周有白边
- r - 来自数据框的堆积条形图
- pyspark - pyspark数据框检查字符串是否包含子字符串