如何将数据从复选框 (html) 导入数据库 ASP.NET Core MVC
Posted
技术标签:
【中文标题】如何将数据从复选框 (html) 导入数据库 ASP.NET Core MVC【英文标题】:How to import data from checkbox (html) to database ASP.NET Core MVC 【发布时间】:2020-11-23 19:54:00 【问题描述】:我有一个客人列表,存储在我的数据库中。创建聚会后,我希望用户能够邀请客人参加聚会。
为此,我有两个具有一对多关系的表。在第一个表(guests)中,我有客人的信息,在第二个表(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。
谢谢
【问题讨论】:
能否提供代码中涉及的所有类供我们参考? 【参考方案1】:首先要注意的是,您在动作中有一个用于客人的字符串数组,但我怀疑这应该是一个整数数组。您还可以有一个通用的整数列表,它也应该可以工作。
以下内容对我有用 - 请注意,如果未选中任何复选框,则 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");
【讨论】:
它实际上不起作用。这就是我想要做的:在邀请了一些客人之后(通过选择复选框),稍后,如果我想添加或邀请更多客人,我想通过查看他们来查看被邀请的客人(我已经邀请了他们)用他们选中的复选框。 如果你使用我写的代码,这行得通吗?这就是你的起点 - 注释掉你的代码并试一试以上是关于如何将数据从复选框 (html) 导入数据库 ASP.NET Core MVC的主要内容,如果未能解决你的问题,请参考以下文章