【发布时间】:2021-03-24 17:06:26
【问题描述】:
我正在尝试创建一个可以一次编辑多个值的视图。该视图由列表中的多行组成,我想在其中选中一个复选框以将布尔值 EnableAlertsUpload 更改为 True 或 False,如下图所示:
当按下更新按钮时,应该调用IActionResult Edit,它会更新数据库中的所有EnableAlertsUpload 布尔值。该数据库是使用带有 Entity Framework Core 的 Code First 方法制作的。
当我现在按下更新按钮时,将创建一条新记录,并且所有值都设置为NULL。所以看来我在存储库中的SaveDevice 方法存在问题
警报控制器
public ViewResult Devices()
=> View(new DevicesViewModel
{
Devices = repo.getDevices()
});
[HttpPost]
public IActionResult Edit(Devices devices)
{
repo.SaveDevice(devices);
return RedirectToAction();
}
存储库
public void SaveDevice(Devices devices)
{
if (devices.objid == 0)
{
db.Devices.Add(devices);
}
else
{
Devices dbEntry = db.Devices
.FirstOrDefault(p => p.objid == devices.objid);
if (dbEntry != null)
{
dbEntry.objid = devices.objid;
dbEntry.device = devices.device;
dbEntry.group = devices.group;
dbEntry.host = devices.host;
dbEntry.EnableAlertsUpload = devices.EnableAlertsUpload;
}
}
db.SaveChanges();
}
设备
public partial class Devices
{
[Key()]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int objid { get; set; }
public string group { get; set; }
public string device { get; set; }
public string host { get; set; }
public bool EnableAlertsUpload { get; set; }
}
DevicesViewModel
public class DevicesViewModel : PageModel
{
[BindProperty]
public List<Devices> Devices { get; set; }
}
设备视图
@model Models.ViewModels.DevicesViewModel
<form asp-action="Edit" method="post">
<table class="table">
<tr>
<th>Id</th>
<th>Device</th>
<th>Group</th>
<th>Host</th>
<th>Enabled Alerts Update</th>
</tr>
@for (var i = 0; i < Model.Devices.Count(); i++)
{
<tr>
<td>
<input type="hidden" asp-for="Devices[i].objid" />
@Model.Devices[i].objid
</td>
<td>@Model.Devices[i].device</td>
<td>@Model.Devices[i].group</td>
<td>@Model.Devices[i].host</td>
<td><input asp-for="Devices[i].EnableAlertsUpload"/></td>
</tr>
}
</table>
<button input type="submit" value="Edit">Update</button>
</form>
【问题讨论】:
-
您的 POST 编辑方法只需要一个
Devices对象,而不是它们的集合。试试public IActionResult Edit(Devices[] devices)。您的存储库方法也需要更改以期望设备列表。然后,您将需要对它们进行 foreach 循环。
标签: asp.net-mvc asp.net-core entity-framework-core blazor