C# 复选框列表更新问题

C# 复选框列表更新问题,c#,asp.net-core-mvc,entity-framework-core,C#,Asp.net Core Mvc,Entity Framework Core,我正在使用ASP.NET核心MVC、EntityFramework核心和C# 在[HttpPost]编辑操作方法CustomerDeviceController上将复选框列表值更新到数据库中的CustomerDevice表时遇到问题。CustomerDevice表是一个联接表,在Customer表和Device表之间具有多对多的连接 CustomerDeviceController的“我的索引”操作方法显示“我的客户”表中的客户列表。我有一个标记为“编辑”的ActionLink,它将CustId

我正在使用ASP.NET核心MVC、EntityFramework核心和C#

在[HttpPost]编辑操作方法CustomerDeviceController上将复选框列表值更新到数据库中的CustomerDevice表时遇到问题。CustomerDevice表是一个联接表,在Customer表和Device表之间具有多对多的连接

CustomerDeviceController的“我的索引”操作方法显示“我的客户”表中的客户列表。我有一个标记为“编辑”的ActionLink,它将CustId值传递给CustomerDeviceController[HttpGet]编辑(int?id)操作方法,然后将分配给CustId的所有选定的DevId值显示到复选框列表中,这部分工作正常

当我现在尝试更新复选框列表值时,它会添加我选择删除的DevId值和我希望保留的DevId值

例如:如果我最初为CustId 1006添加了DevId值(1、3、4和7),然后决定编辑以仅删除DevId值1,它实际上会删除DevId值(3、4和7),并保留DevId值1

型号

public class CheckBoxListItem
{
    public int ID { get; set; }
    public string Display { get; set; }
    public bool IsChecked { get; set; }
}

public class Customer
{
    public int CustId { get; set; }
    public string CustDisplayName { get; set; }
    public string CustFirstName { get; set; }
    public string CustLastName { get; set; }

    public List<CustomerDevice> CustomerDevices { get; set; }
}

public class CustomerDevice
{
    public int CustId { get; set; }
    public int DevId { get; set; }

    public Customer Customer { get; set; }
    public Device Device { get; set; }
}

public class Device
{
    public int DevId { get; set; }
    public string DevType { get; set; }

    public List<CustomerDevice> CustomerDevices { get; set; }
}

public class WebFormContext : DbContext
{
    public WebFormContext(DbContextOptions<WebFormContext> options)
        : base(options)
    { }

    public DbSet<Customer> Customers { get; set; }
    public DbSet<Device> Devices { get; set; }
    public DbSet<CustomerDevice> CustomerDevices { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>()
            .HasKey(c => c.CustId);

        modelBuilder.Entity<Customer>()
            .Property(c => c.CustDisplayName)
            .HasColumnType("varchar(100)")
            .HasMaxLength(100)
            .IsRequired();

        modelBuilder.Entity<Customer>()
            .Property(c => c.CustFirstName)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50);

        modelBuilder.Entity<Customer>()
            .Property(c => c.CustLastName)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50);

        modelBuilder.Entity<Device>()
            .HasKey(d => d.DevId);

        modelBuilder.Entity<Device>()
            .Property(d => d.DevType)
            .HasColumnType("varchar(50)")
            .HasMaxLength(50)
            .IsRequired();

        modelBuilder.Entity<CustomerDevice>()
        .HasKey(c => new { c.CustId, c.DevId });

        modelBuilder.Entity<CustomerDevice>()
            .HasOne(cd => cd.Customer)
            .WithMany(c => c.CustomerDevices)
            .HasForeignKey(cd => cd.CustId);

        modelBuilder.Entity<CustomerDevice>()
            .HasOne(cd => cd.Device)
            .WithMany(d => d.CustomerDevices)
            .HasForeignKey(cd => cd.DevId);
    }
}
公共类CheckBoxListItem
{
公共int ID{get;set;}
公共字符串显示{get;set;}
已检查公共布尔值{get;set;}
}
公共类客户
{
public int CustId{get;set;}
公共字符串CustDisplayName{get;set;}
公共字符串CustFirstName{get;set;}
公共字符串CustLastName{get;set;}
公共列表CustomerDevices{get;set;}
}
公共类CustomerDevice
{
public int CustId{get;set;}
公共int设备{get;set;}
公共客户客户{get;set;}
公用设备设备{get;set;}
}
公共类设备
{
公共int设备{get;set;}
公共字符串DevType{get;set;}
公共列表CustomerDevices{get;set;}
}
公共类WebFormContext:DbContext
{
公共WebFormContext(DbContextOptions选项)
:基本(选项)
{ }
公共数据库集客户{get;set;}
公共数据库集设备{get;set;}
公共DbSet CustomerDevices{get;set;}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.Entity()
.HasKey(c=>c.CustId);
modelBuilder.Entity()
.Property(c=>c.CustDisplayName)
.HasColumnType(“varchar(100)”)
.HasMaxLength(100)
.IsRequired();
modelBuilder.Entity()
.Property(c=>c.CustFirstName)
.HasColumnType(“varchar(50)”)
.HasMaxLength(50);
modelBuilder.Entity()
.Property(c=>c.CustLastName)
.HasColumnType(“varchar(50)”)
.HasMaxLength(50);
modelBuilder.Entity()
.HasKey(d=>d.DevId);
modelBuilder.Entity()
.Property(d=>d.DevType)
.HasColumnType(“varchar(50)”)
.HasMaxLength(50)
.IsRequired();
modelBuilder.Entity()
.HasKey(c=>new{c.CustId,c.DevId});
modelBuilder.Entity()
.HasOne(cd=>cd.Customer)
.有许多(c=>c.CustomerDevices)
.HasForeignKey(cd=>cd.CustId);
modelBuilder.Entity()
.HasOne(cd=>cd.Device)
.有许多(d=>d.客户设备)
.HasForeignKey(cd=>cd.DevId);
}
}
视图模型

public class CustomerDeviceFormViewModel
{
    public int CustId { get; set; }
    public string CustDisplayName { get; set; }
    public List<CheckBoxListItem> Devices { get; set; }
}
<div class="checkbox">
<label>
    @Html.HiddenFor(x => x.ID)
    @Html.CheckBoxFor(x => x.IsChecked)
    @Html.LabelFor(x => x.IsChecked, Model.Display)
</label>
<br />
公共类CustomerDeviceFormViewModel
{
public int CustId{get;set;}
公共字符串CustDisplayName{get;set;}
公共列表设备{get;set;}
}
控制器

public class CustomerDeviceController : Controller
{
    // GET: /<controller>/
    public IActionResult Index()
    {
        return View(db.Customers.ToList());
    }


    public ActionResult Edit(int? id)
    {
        Customer customer = db.Customers.SingleOrDefault(c => c.CustId == id);
        if (customer == null)
        {
            return NotFound();
        }
        // Get all devices
        var deviceList = db.Devices.ToList();
        // Get the selected device ID's for the customer
        IEnumerable<int> selectedDevices = db.CustomerDevices
            .Where(x => x.CustId == id).Select(x => x.DevId);
        // Build view model
        var model = new CustomerDeviceFormViewModel()
        {
            CustId = customer.CustId,
            CustDisplayName = customer.CustDisplayName,
            Devices = deviceList.Select(x => new CheckBoxListItem()
            {
                ID = x.DevId,
                Display = x.DevType,
                IsChecked = selectedDevices.Contains(x.DevId)
            }).ToList()
        };
        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(CustomerDeviceFormViewModel vmEdit)
    {
        if (ModelState.IsValid)
        {
            Customer customer = db.Customers
                       .Include(c => c.CustomerDevices)
                       .SingleOrDefault(c => c.CustId == vmEdit.CustId);

            if (customer == null)
            {
                return NotFound();
            }

            IEnumerable<int> selectedDevices = vmEdit.Devices.Where(x => x.IsChecked).Select(x => x.ID);

            // Add the new selected devices
            foreach (int deviceId in selectedDevices)
            {
                var customerDevice = customer.CustomerDevices.FirstOrDefault(cd => cd.DevId == deviceId);
                if (customerDevice != null)
                {
                    customer.CustomerDevices.Remove(customerDevice);
                }
                else
                {
                    CustomerDevice custDevice = new CustomerDevice
                    {
                        CustId = customer.CustId,
                        DevId = deviceId
                    };
                    customer.CustomerDevices.Add(custDevice);
                }
            }

            // Update the customer
            db.Customers.Update(customer); //or just db.Update(customer); same thing
                                           // Save and redirect
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(vmEdit);
    }
}
公共类CustomerDeviceController:控制器
{
//获取://
公共IActionResult索引()
{
返回视图(db.Customers.ToList());
}
公共行动结果编辑(int?id)
{
Customer=db.Customers.SingleOrDefault(c=>c.CustId==id);
如果(客户==null)
{
返回NotFound();
}
//获取所有设备
var deviceList=db.Devices.ToList();
//为客户获取所选的设备ID
IEnumerable selectedDevices=db.CustomerDevices
。其中(x=>x.CustId==id)。选择(x=>x.DevId);
//构建视图模型
var模型=新CustomerDeviceFormViewModel()
{
CustId=customer.CustId,
CustDisplayName=customer.CustDisplayName,
Devices=deviceList.Select(x=>new CheckBoxListItem()
{
ID=x.DevId,
Display=x.DevType,
IsChecked=selectedDevices.Contains(x.DevId)
})托利斯先生()
};
返回视图(模型);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果编辑(CustomerDeviceFormViewModel vmEdit)
{
if(ModelState.IsValid)
{
客户=数据库客户
.包括(c=>c.CustomerDevices)
.SingleOrDefault(c=>c.CustId==vmEdit.CustId);
如果(客户==null)
{
返回NotFound();
}
IEnumerable selectedDevices=vmEdit.Devices.Where(x=>x.IsChecked)。选择(x=>x.ID);
//添加新的选定设备
foreach(选定设备中的int deviceId)
{
var customerDevice=customer.CustomerDevices.FirstOrDefault(cd=>cd.DevId==deviceId);
如果(customerDevice!=null)
{
customer.CustomerDevices.Remove(customerDevice);
}
其他的
{
CustomerDevice custDevice=新CustomerDevice
{
CustId=customer.CustId,
设备ID=设备ID
};
customer.CustomerDevices.Add(custDevice);
}
}
//更新客户信息
db.Customers.Update(cu
<div class="form-group">
    Please select the Devices to assign to <b>@Html.DisplayFor(c => c.CustDisplayName)</b>
</div>

<div class="form-group">
    @Html.EditorFor(x => x.Devices)
</div>

@Html.HiddenFor(c => c.CustId)

<div class="form-group">
    <button type="submit" class="btn btn-primary">Submit</button>
</div>