本文介绍了Asp.net核心MVC编辑数据库中的checkboxlist值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我无法在[HttpPost]编辑操作方法CustomerDeviceController上将CheckBoxList值更新到我的数据库中的CustomerDevice表。 索引操作方法CustomerDeviceController显示Customers表中的Customers列表。我有一个标记为编辑的ActionLink,它将CustId值传递给CustomerDeviceController [HttpGet]编辑(int?id)操作方法,然后显示分配给CustBox的所有选定的DevId值到CheckBoxList,这部分工作正常。 我遇到的问题是,如果我最初为CustId 1006添加DevId值(1,3,4和7),然后决定仅删除DevId值1实际上删除DevId值(3,4和7)并留下DevId值1. 所以它似乎添加了我选择删除的DevId值和DevId值我想保持它删除。我已经包含了我的模型,ViewModel,Controller和Views。我希望有人能看到我做错了或需要添加以纠正问题。 模特 public class CheckBoxListItem { public int ID { get ; set ; } public string 显示{ get ; set ; } public bool IsChecked { get ; set ; } } public class 客户 { public int CustId { get ; set ; } public string CustDisplayName { get ; set ; } public string CustFirstName { get ; set ; } public string CustLastName { get ; set ; } public string CustCompanyName { get ; set ; } public string CustAddress { get ; set ; } public string CustPhoneNumber { get ; set ; } public string CustMobileNumber { get ; set ; } public string CustEmailAddress { get ; set ; } public 列表< customerdevice> CustomerDevices { get ; set ; } } public class CustomerDevice { public int CustId { get ; set ; } public int DevId { get ; set ; } public 客户客户{获取; set ; } public 设备设备{ get ; set ; } } public class 设备 { public int DevId { get ; set ; } public string DevType { get ; set ; } public 列表< customerdevice> CustomerDevices { get ; set ; } } public class WebFormContext:DbContext { public WebFormContext( DbContextOptions< webformcontext> options): base (options) {} public DbSet< customer>客户{获取; set ; } public DbSet< state>国家{获取; set ; } public DbSet< device>设备{获取; set ; } public DbSet< customerdevice> CustomerDevices { get ; set ; } 受保护 覆盖 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< customer>() .Property(c = > c.CustCompanyName)。 HasColumnType( varchar(50)) .HasMaxLength( 50 ); modelBuilder.Entity< customer>() .Property(c = > c.CustAddress)。 HasColumnType( varchar(100)) .HasMaxLength( 100 ) .IsRequired(); modelBuilder.Entity< customer>() .Property(c = > c.CustPhoneNumber)。 HasColumnType( varchar(12)) .HasMaxLength( 12 ); modelBuilder.Entity< customer>() .Property(c = > c.CustMobileNumber)。 HasColumnType( varchar(12)) .HasMaxLength( 12 ); modelBuilder.Entity< customer>() .Property(c = > c.CustEmailAddress)。 HasColumnType( varchar(320)) .HasMaxLength( 320 ); 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); } } ViewModel public class CustomerDeviceFormViewModel { public int CustId { get ; set ; } public string CustDisplayName { get ; set ; } public 列表< checkboxlistitem>设备{获取; set ; } } CustomerDeviceController public class CustomerDeviceController:Controller { private WebFormContext db; public CustomerDeviceController(WebFormContext context) { db = context; } // GET:/< controller> / public IActionResult Index() { return View(db.Customers.ToList()); } public ActionResult Create( int ?id) { if (id == null ) { return NotFound(); } var customervm = new CustomerDeviceFormViewModel(); {客户客户= db.Customers.SingleOrDefault(c = > c.CustId == id); if (customer == null ) { return NotFound(); } customervm.CustId = customer.CustId; customervm.CustDisplayName = customer.CustDisplayName; // 检索CheckBoxList的设备列表 var deviceList = db.Devices.ToList(); var checkBoxListItems = new List< checkboxlistitem>(); foreach ( var device in deviceList) { checkBoxListItems.Add( new CheckBoxListItem() { ID = device.DevId,显示= device.DevType, IsChecked = false // 在创建视图中,默认情况下未选择任何设备 }); } customervm.Devices = checkBoxListItems; return 查看(customervm); } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(CustomerDeviceFormViewModel vm) { if (ModelState.IsValid) { foreach ( var deviceId in vm.Devices.Where(x = > x.IsChecked).Select(x = > x.ID)) { var customerDevices = new CustomerDevice { CustId = vm .CustId, DevId = deviceId }; db.CustomerDevices.Add(customerDevices); } db.SaveChanges(); return RedirectToAction( Index); } return 查看(vm); } public ActionResult Edit( int ?id) {客户客户= db.Customers.SingleOrDefault(c = > c.CustId == id); if (customer == null ) { return NotFound(); } // 获取所有设备 var deviceList = db.Devices.ToList(); // 获取客户的所选设备ID IEnumerable< int> selectedDevices = db.CustomerDevices .Where(x = > x.CustId == id).Select(x = > x.DevId); // 构建视图模型 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 查看(模型); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(CustomerDeviceFormViewModel vmEdit) { if (ModelState.IsValid) {客户客户= db.Customers 。包含(c = > c.CustomerDevices) .SingleOrDefault(c = > c.CustId = = vmEdit.CustId); if (customer == null ) { return NotFound(); } IEnumerable< int> selectedDevices = vmEdit.Devices.Where(x = > x.IsChecked)。选择(x = > x.ID); // 添加新选择的设备 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); } } // 更新客户 db.Customers.Update(customer); // 或者只是db.Update(客户);相同的事情 // 保存并重定向 db.SaveChanges (); return RedirectToAction( Index); } return 查看(vmEdit); } } 编辑视图 @ using(Html.BeginForm(Edit,CustomerDevice)) { < div class = form-group > 请选择要分配的设备< / div > ; < div class = 表单-group > @ Html.EditorFor(x => x.Devices) < / div > @ Html.HiddenFor(c => c.CustId) < div 类 = 表格 - group > < 按钮 类型 = 提交 class = btn btn-primary > 提交< / button > < / div > } Shared\EditorTemplates\CheckBoxListItems.chtml查看 < div class = 复选框 > < label > @ Html.HiddenFor(x => x.ID) @ Html.CheckBoxFor(x => x.IsChecked) @ Html.LabelFor(x => x.IsChecked,Model.Display) < / label > < br > < / div > 编辑视图(源代码),显示CheckBoxList值: < !DOCTYPE html > < html > < head > < meta charset = utf-8 / > < meta name = viewport content = width = device-width,initial-scale = 1.0 / > < title > 编辑设备(s )到客户 - WebForm < / title > < / head > < body > < div class = navbar navbar-inverse navbar-fixed-top > < div class = 容器 > < div class = navbar-header > < 按钮 类型 = 按钮 class = navbar-toggle data-toggle = 折叠 data-target = .navbar-collapse > < span class = 仅限sr > 切换导航< / span > < span class = icon-bar > < / span > < span class = 图标栏 > < / span > < span class = icon-bar > < ; / span > < / button > < a class = navbar-brand href = / > WebForm < / a > < / div > < div class = navbar-collapse collapse > < ul class = nav navbar-nav > < li > < a href = / > 主页 < / a > < / li > < li > <a href=\"/Customer\">Customer</a></li> <li><a href=\"/CustomerDevice\">Customer Device</a></li> <li><a href=\"/Home/Contact\">Contact</a ></li> </ul> </div> </div> </div> <div class=\"container body-content\"> <h2>Edit Device(s) to Customer</h2> <form action=\"/CustomerDevice/Edit/1006\" method=\"post\"> <div class=\"form-group\"> Please select the Devices to assign to Mary Doe </div> <div class=\"form-group\"> <div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_0__ID\" name=\"Devices[0].ID\" type=\"hidden\" value=\"1\" /> <input data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_0__IsChecked\" name=\"Devices[0].IsChecked\" type=\"c heckbox\" value=\"true\" /> <label for=\"Devices_0__IsChecked\">Desktop</label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_1__ID\" name=\"Devices[1].ID\" type=\"hidden\" value=\"2\" /> <input data-val=\"true\" data-v al-required=\"The IsChecked field is required.\" id=\"Devices_1__IsChecked\" name=\"Devices[1].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_1__IsChecked\">Laptop</label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_2__ID\" name=\"Devices[2].ID\" type=\"hidd en\" value=\"3\" /> <input data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_2__IsChecked\" name=\"Devices[2].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_2__IsChecked\">Keyboard</label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_3__ID\" name=\"Devices[3].ID\" type=\"hidden\" value=\"4\" /> <input data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_3__IsChecked\" name=\"Devices[3].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_3__IsChecked\">Mouse</label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_4__ID\" name=\"Devices[4].ID\" type=\"hidden\" value=\"5\" /> <input data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_4__IsChecked\" name=\"Devices[4].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_4__IsChecked\">Headset< /label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_5__ID\" name=\"Devices[5].ID\" type=\"hidden\" value=\"6\" /> <input data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_5__IsChecked\" name=\"Devices[5].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_5__IsChecked\">iPad</label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_6__ID\" name=\"Devices[6].ID\" type=\"hidden\" value=\"7\" /> <input data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_6__IsChecked\" name=\"Devices[6].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_6__IsChecked\">Power Adapter</label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_7__ID\" name=\"Devices[7].ID\" type=\"hidden\" value=\"8\" /> <input data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_7__IsChecked\" name=\"Devices[7].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_7__IsChecked\">Phone</label> </label> <br> </div> </div> <input data-val=\"true\" data-val-required=\"The CustId field is required.\" id=\"CustId\" name=\"CustId\" type=\"hidden\" value=\"1006\" /> <div class=\"form-group\"> <button type=\"submit\" class=\"btn btn-primary\">Submit</button> </div> <input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"CfDJ8OavugUS_IJDuIPr6xpVUkAb3CZQhxvBHON5YMfwP6vLHdCL6yuyiD3HruUggKlQpJ2y76owQYcGwjszMdBzS5_YJxx1D1chcDeI_8RMGmDQW-S6yT0BV4yjVVnJYFJgB65jvQOtIaMn9hY593axunQ\" /><input name=\"Devices[0].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[1].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[2].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[3].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[4].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[5].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[6].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[7].IsChecked\" type=\"hidden\" value=\"false\" /></form> <hr> <p>© 2016 - WebForm</p> </div> <script src=\"/lib/jquery/dist/jquery.js\"></script> <script src=\"/lib/bootstrap/dist/js/bootstrap.js\"></script> <script src=\"/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo\"></script> <script src=\"/lib/jquery-validation/dist/jquery.validate.js\"></script> <script src=\"/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js\"></script> <!-- Visual Studio Browser Link --> <script type=\"application/json\" id=\"__browserLink_initializationData\"> {\"requestId\":\"359eef69ee5348909cbbb8b0835fbb27\",\"requestMappingFromServer\":false} </script> <script type=\"text/javascript\" src=\"http://localhost:53061/6ddbe519e8204b1d8cafa73b53ac5a72/browserLink\" async=\"async\"></script> <!-- End Browser Link --> </body> </html> Edit View (Source Code) that shows CheckBoxList Values assigned to CustId 1006: <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Edit Device(s) to Customer - WebForm</title> </head> <body> <div class=\"navbar navbar-inverse navbar-fixed-top\"> <div class=\"container\"> <div class=\"navbar-header\"> <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".navbar-collapse\"> <span class=\"sr-only\">Toggle navigation</span> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> </button> <a class=\"navbar-brand\" href=\"/\">WebForm</a> </div> <div class=\"navbar-collapse collapse\"> <ul class=\"nav navbar-nav\"> <li><a href=\"/\">Home</a></li> & lt;li><a href=\"/Customer\">Customer</a></li> <li><a href=\"/CustomerDevice\">Customer Device</a></li> <li><a href=\"/Home/Contact\">Contact</a></li> </ul> </div> </div> </div> <div class=\"container body-content\"> <h2>Edit Device(s) to Customer</h2> <form action=\"/CustomerDevice/Edit/1006\" method=\"post\"> <div class=\"form-group\"> Please select the Devices to assign to Mary Doe </div> <div class=\"form-group\"> <div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_0__ID\" name=\"Devices[0].ID\" type=\"hidden\" value=\"1\" /> <input checked=\"checked\" data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_0__IsChecked\" name=\"Devices[0].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_0__IsChecked\">Desktop</label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_1__ID\" name=\"Devices[1].ID\" type=\"hidden\" value=\"2\" /> <input data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_1__IsChecked\" name=\"Devices[1].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_1__IsChecked\">Laptop</label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_2__ID\" name=\"Devices[2].ID\" type=\"hidden\" value=\"3\" /> <input checked=\"checked\" data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_2 __IsChecked\" name=\"Devices[2].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_2__IsChecked\">Keyboard</label > </label> <br> </div><div class=\"checkbox\"> <label> <input data-v al=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_3__ID\" name=\"Devices[3].ID\" type=\"hidden\" value=\"4\" /> <input checked=\"checked\" data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_3__IsChecked\" name=\"Devices[3].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_3__IsChecked\">Mouse</label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID fiel d is required.\" id=\"Devices_4__ID\" name=\"Devices[4].ID\" type=\"hidden\" value=\"5\" /> <input data-val=\"tru e\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_4__IsChecked\" name=\"Devices[4].IsChecked\" type=\"checkbox\" value=\"true\" /> < label for=\"Devices_4__IsChecked\">Headset</label> </label> <br> </div><div class=\"checkb ox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_5__ID\" name=\"Devices[5].ID\" type=\"hidden\" value=\"6\" /> <input data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_5__IsChecked\" name=\"Devices[5].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_5__IsChecked\">iPad</label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_6__ID\" name=\"Devices[6].ID\" type=\"hidden\" value=\"7\" /> <input checked=\"checked\" data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_6__IsChecked\" name=\"Devices[6].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_6__IsChecked\">Power Adapter</label> </label> <br> </div><div class=\"checkbox\"> <label> <input data-val=\"true\" data-val-required=\"The ID field is required.\" id=\"Devices_7__ID\" name=\"Devices[7].ID\" type=\"hidden\" value=\"8\" /> <input data-val=\"true\" data-val-required=\"The IsChecked field is required.\" id=\"Devices_7__IsChecked\" name=\"Devices[7].IsChecked\" type=\"checkbox\" value=\"true\" /> <label for=\"Devices_7__IsChecked\">Phone</label> </label> <br> </div> </div> <input data-val=\"true\" data-val-required=\"The CustId field is required.\" id=\"CustId\" name=\"CustId\" type=\"hidden\" value=\"1006\" /> <div class=\"form-group\"> <button type=\"submit\" class=\"btn btn-primary\">Submit</button> </div> <input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"CfDJ8OavugUS_IJDuIPr6xpVUkAPOUb8w4S2Vnz2eyIV8YmkPTHJ_uvBT34rWHhobOnSJn4zwQ2tmIW1Ib3ynRht8S8j8a6WEQP3DCpB15DotmCyxr3fYyTIM_lGrE2sNXqfYfjscGCHOhY-irNE3h5jB9k\" /><input name=\"Devices[0].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[1].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[2].IsChecked\" type=\"hidden\" value=\"false\" /><input name =\"Devices[3].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[4].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[5].IsChecked\" type=\"hidden\" value=\"false\" /><input name =\"Devices[6].IsChecked\" type=\"hidden\" value=\"false\" /><input name=\"Devices[7].IsChecked\" type=\"hidden\" value=\"false\" /></form> <hr> <p>© 2016 - WebForm</p> </div> <script src=\"/lib/jquery/dist/jquery.js\"></script> <script src=\"/lib/bootstrap/dist/js/bootstrap.js\"></script> <script src=\"/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo\"></script> <script src=\"/lib/jquery-validation/dist/jquery.validate.js\"></script> <script src=\"/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js\"></script> <!-- Visual Studio Browser Link --> <script type=\"application/json\" id=\"__browserLink_initializationData\"& gt; {\"requestId\":\"db2020dde36447d49b6a626dad3c3c43\",\"requestMappingFromServer\":false} </script> <script type=\"text/javascript\" src=\"http://localhost:53061/6ddbe519e8204b1d8cafa73b53ac5a72/browserLink\" async=\"async\"></script> <!-- End Browser Link --> </body> </html> I’m submitting the CheckBoxList values using a Submit Button. What I have tried: I have tried setting breakpoints at various areas in my Edit Post and the va lues seem to be okay to me. But after I update the values they are incorrect. 解决方案 The view which uses CheckBoxListItems.chtml does not seem to included, most likely this is used in a loop for public List<checkboxlistitem> Devices { get;组; }。 Also most of the code is not useful to the question. From this: \"The problem that I’m having is, If I initially added DevId values (1, 3, 4 and 7) for CustId 1006 and then decide to remove just DevId value 1 it actually removes DevId values (3, 4 and 7) and leaves DevId value 1\" This link may help: Model Binding To A List - You’ve Been Haacked[^] As per the link, your array must look something like this (copied from the link): <input type=\"text\" name=\"[0].ID\" value=\"1\" /> --added <input type=\"text\" name=\"[0].Title\" value=\"Curious George\" /> <input type=\"text\" name=\"[0].Author\" value=\"H.A. Rey\" /> <input type=\"text\" name=\"[0].DatePublished\" value=\"2/23/1973\" /> <input type=\"text\" name=\"[1].ID\" value=\"3\" /> --added <input type=\"text\" name=\"[1].Title\" value=\"Code Complete\" /> <input type=\"text\" name=\"[1].Author\" value=\"Steve McConnell\" /> <input type=\"text\" name=\"[1].DatePublished\" value=\"6/9/2004\" /> So most likely your data is being sent with only the 1st row: row[1] row[3] --broken row[4] row[7] --broken And the reason for this (copied from link) Note that the index must be an unbroken sequence of integers starting at 0 and increasing by 1 for each element.I'm having trouble updating the CheckBoxList values to the CustomerDevice table in my Database on the [HttpPost] Edit Action Method CustomerDeviceController.Index Action Method for the CustomerDeviceController displays a list of Customers from my Customers table. I have an ActionLink labeled "Edit" that passes the CustId value to the CustomerDeviceController [HttpGet] Edit(int? id) Action Method which then displays all selected DevId values assigned to the CustId to the CheckBoxList, this part works fine.The problem that I'm having is, If I initially added DevId values (1, 3, 4 and 7) for CustId 1006 and then decide to remove just DevId value 1 it actually removes DevId values (3, 4 and 7) and leaves DevId value 1.So it seems to add the DevId values that I choose to remove and the DevId values that I want to keep it removes. I have included my Models, ViewModel, Controller and Views. I'm hoping someone can see what I'm doing wrong or need to add to correct the issue.Modelspublic 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 string CustCompanyName { get; set; } public string CustAddress { get; set; } public string CustPhoneNumber { get; set; } public string CustMobileNumber { get; set; } public string CustEmailAddress { 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<state> States { 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<customer>() .Property(c => c.CustCompanyName) .HasColumnType("varchar(50)") .HasMaxLength(50); modelBuilder.Entity<customer>() .Property(c => c.CustAddress) .HasColumnType("varchar(100)") .HasMaxLength(100) .IsRequired(); modelBuilder.Entity<customer>() .Property(c => c.CustPhoneNumber) .HasColumnType("varchar(12)") .HasMaxLength(12); modelBuilder.Entity<customer>() .Property(c => c.CustMobileNumber) .HasColumnType("varchar(12)") .HasMaxLength(12); modelBuilder.Entity<customer>() .Property(c => c.CustEmailAddress) .HasColumnType("varchar(320)") .HasMaxLength(320); 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); } }ViewModelpublic class CustomerDeviceFormViewModel{ public int CustId { get; set; } public string CustDisplayName { get; set; } public List<checkboxlistitem> Devices { get; set; }}CustomerDeviceControllerpublic class CustomerDeviceController : Controller { private WebFormContext db; public CustomerDeviceController(WebFormContext context) { db = context; } // GET: /<controller>/ public IActionResult Index() { return View(db.Customers.ToList()); } public ActionResult Create(int? id) { if (id == null) { return NotFound(); } var customervm = new CustomerDeviceFormViewModel(); { Customer customer = db.Customers.SingleOrDefault(c => c.CustId == id); if (customer == null) { return NotFound(); } customervm.CustId = customer.CustId; customervm.CustDisplayName = customer.CustDisplayName; // Retrieves list of Devices for CheckBoxList var deviceList = db.Devices.ToList(); var checkBoxListItems = new List<checkboxlistitem>(); foreach (var device in deviceList) { checkBoxListItems.Add(new CheckBoxListItem() { ID = device.DevId, Display = device.DevType, IsChecked = false //On the create view, no devices are selected by default }); } customervm.Devices = checkBoxListItems; return View(customervm); } } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(CustomerDeviceFormViewModel vm) { if (ModelState.IsValid) { foreach (var deviceId in vm.Devices.Where(x => x.IsChecked).Select(x => x.ID)) { var customerDevices = new CustomerDevice { CustId = vm.CustId, DevId = deviceId }; db.CustomerDevices.Add(customerDevices); } db.SaveChanges(); return RedirectToAction("Index"); } return View(vm); } 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); } }Edit View@using (Html.BeginForm("Edit", "CustomerDevice")){ <div class="form-group"> Please select the Devices to assign </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>}Shared\EditorTemplates\CheckBoxListItems.chtml View<div class="checkbox"> <label> @Html.HiddenFor(x => x.ID) @Html.CheckBoxFor(x => x.IsChecked) @Html.LabelFor(x => x.IsChecked, Model.Display) </label> <br></div>Edit View (Source Code) that shows CheckBoxList Values:<!DOCTYPE html><html><head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Edit Device(s) to Customer - WebForm</title> </head><body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">WebForm</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="/">Home</a></li> <li><a href="/Customer">Customer</a></li> <li><a href="/CustomerDevice">Customer Device</a></li> <li><a href="/Home/Contact">Contact</a></li> </ul> </div> </div> </div> <div class="container body-content"> <h2>Edit Device(s) to Customer</h2><form action="/CustomerDevice/Edit/1006" method="post"> <div class="form-group"> Please select the Devices to assign to Mary Doe </div> <div class="form-group"> <div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_0__ID" name="Devices[0].ID" type="hidden" value="1" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_0__IsChecked" name="Devices[0].IsChecked" type="checkbox" value="true" /> <label for="Devices_0__IsChecked">Desktop</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_1__ID" name="Devices[1].ID" type="hidden" value="2" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_1__IsChecked" name="Devices[1].IsChecked" type="checkbox" value="true" /> <label for="Devices_1__IsChecked">Laptop</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_2__ID" name="Devices[2].ID" type="hidden" value="3" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_2__IsChecked" name="Devices[2].IsChecked" type="checkbox" value="true" /> <label for="Devices_2__IsChecked">Keyboard</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_3__ID" name="Devices[3].ID" type="hidden" value="4" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_3__IsChecked" name="Devices[3].IsChecked" type="checkbox" value="true" /> <label for="Devices_3__IsChecked">Mouse</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_4__ID" name="Devices[4].ID" type="hidden" value="5" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_4__IsChecked" name="Devices[4].IsChecked" type="checkbox" value="true" /> <label for="Devices_4__IsChecked">Headset</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_5__ID" name="Devices[5].ID" type="hidden" value="6" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_5__IsChecked" name="Devices[5].IsChecked" type="checkbox" value="true" /> <label for="Devices_5__IsChecked">iPad</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_6__ID" name="Devices[6].ID" type="hidden" value="7" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_6__IsChecked" name="Devices[6].IsChecked" type="checkbox" value="true" /> <label for="Devices_6__IsChecked">Power Adapter</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_7__ID" name="Devices[7].ID" type="hidden" value="8" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_7__IsChecked" name="Devices[7].IsChecked" type="checkbox" value="true" /> <label for="Devices_7__IsChecked">Phone</label> </label> <br></div> </div><input data-val="true" data-val-required="The CustId field is required." id="CustId" name="CustId" type="hidden" value="1006" /> <div class="form-group"> <button type="submit" class="btn btn-primary">Submit</button> </div><input name="__RequestVerificationToken" type="hidden" value="CfDJ8OavugUS_IJDuIPr6xpVUkAb3CZQhxvBHON5YMfwP6vLHdCL6yuyiD3HruUggKlQpJ2y76owQYcGwjszMdBzS5_YJxx1D1chcDeI_8RMGmDQW-S6yT0BV4yjVVnJYFJgB65jvQOtIaMn9hY593axunQ" /><input name="Devices[0].IsChecked" type="hidden" value="false" /><input name="Devices[1].IsChecked" type="hidden" value="false" /><input name="Devices[2].IsChecked" type="hidden" value="false" /><input name="Devices[3].IsChecked" type="hidden" value="false" /><input name="Devices[4].IsChecked" type="hidden" value="false" /><input name="Devices[5].IsChecked" type="hidden" value="false" /><input name="Devices[6].IsChecked" type="hidden" value="false" /><input name="Devices[7].IsChecked" type="hidden" value="false" /></form> <hr> <p>© 2016 - WebForm</p> </div> <script src="/lib/jquery/dist/jquery.js"></script> <script src="/lib/bootstrap/dist/js/bootstrap.js"></script> <script src="/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo"></script> <script src="/lib/jquery-validation/dist/jquery.validate.js"></script> <script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script><!-- Visual Studio Browser Link --><script type="application/json" id="__browserLink_initializationData"> {"requestId":"359eef69ee5348909cbbb8b0835fbb27","requestMappingFromServer":false}</script><script type="text/javascript" src="http://localhost:53061/6ddbe519e8204b1d8cafa73b53ac5a72/browserLink" async="async"></script><!-- End Browser Link --></body></html>Edit View (Source Code) that shows CheckBoxList Values assigned to CustId 1006:<!DOCTYPE html><html><head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Edit Device(s) to Customer - WebForm</title> </head><body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">WebForm</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="/">Home</a></li> <li><a href="/Customer">Customer</a></li> <li><a href="/CustomerDevice">Customer Device</a></li> <li><a href="/Home/Contact">Contact</a></li> </ul> </div> </div> </div> <div class="container body-content"> <h2>Edit Device(s) to Customer</h2><form action="/CustomerDevice/Edit/1006" method="post"> <div class="form-group"> Please select the Devices to assign to Mary Doe </div> <div class="form-group"> <div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_0__ID" name="Devices[0].ID" type="hidden" value="1" /> <input checked="checked" data-val="true" data-val-required="The IsChecked field is required." id="Devices_0__IsChecked" name="Devices[0].IsChecked" type="checkbox" value="true" /> <label for="Devices_0__IsChecked">Desktop</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_1__ID" name="Devices[1].ID" type="hidden" value="2" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_1__IsChecked" name="Devices[1].IsChecked" type="checkbox" value="true" /> <label for="Devices_1__IsChecked">Laptop</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_2__ID" name="Devices[2].ID" type="hidden" value="3" /> <input checked="checked" data-val="true" data-val-required="The IsChecked field is required." id="Devices_2__IsChecked" name="Devices[2].IsChecked" type="checkbox" value="true" /> <label for="Devices_2__IsChecked">Keyboard</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_3__ID" name="Devices[3].ID" type="hidden" value="4" /> <input checked="checked" data-val="true" data-val-required="The IsChecked field is required." id="Devices_3__IsChecked" name="Devices[3].IsChecked" type="checkbox" value="true" /> <label for="Devices_3__IsChecked">Mouse</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_4__ID" name="Devices[4].ID" type="hidden" value="5" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_4__IsChecked" name="Devices[4].IsChecked" type="checkbox" value="true" /> <label for="Devices_4__IsChecked">Headset</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_5__ID" name="Devices[5].ID" type="hidden" value="6" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_5__IsChecked" name="Devices[5].IsChecked" type="checkbox" value="true" /> <label for="Devices_5__IsChecked">iPad</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_6__ID" name="Devices[6].ID" type="hidden" value="7" /> <input checked="checked" data-val="true" data-val-required="The IsChecked field is required." id="Devices_6__IsChecked" name="Devices[6].IsChecked" type="checkbox" value="true" /> <label for="Devices_6__IsChecked">Power Adapter</label> </label> <br></div><div class="checkbox"> <label> <input data-val="true" data-val-required="The ID field is required." id="Devices_7__ID" name="Devices[7].ID" type="hidden" value="8" /> <input data-val="true" data-val-required="The IsChecked field is required." id="Devices_7__IsChecked" name="Devices[7].IsChecked" type="checkbox" value="true" /> <label for="Devices_7__IsChecked">Phone</label> </label> <br></div> </div><input data-val="true" data-val-required="The CustId field is required." id="CustId" name="CustId" type="hidden" value="1006" /> <div class="form-group"> <button type="submit" class="btn btn-primary">Submit</button> </div><input name="__RequestVerificationToken" type="hidden" value="CfDJ8OavugUS_IJDuIPr6xpVUkAPOUb8w4S2Vnz2eyIV8YmkPTHJ_uvBT34rWHhobOnSJn4zwQ2tmIW1Ib3ynRht8S8j8a6WEQP3DCpB15DotmCyxr3fYyTIM_lGrE2sNXqfYfjscGCHOhY-irNE3h5jB9k" /><input name="Devices[0].IsChecked" type="hidden" value="false" /><input name="Devices[1].IsChecked" type="hidden" value="false" /><input name="Devices[2].IsChecked" type="hidden" value="false" /><input name="Devices[3].IsChecked" type="hidden" value="false" /><input name="Devices[4].IsChecked" type="hidden" value="false" /><input name="Devices[5].IsChecked" type="hidden" value="false" /><input name="Devices[6].IsChecked" type="hidden" value="false" /><input name="Devices[7].IsChecked" type="hidden" value="false" /></form> <hr> <p>© 2016 - WebForm</p> </div> <script src="/lib/jquery/dist/jquery.js"></script> <script src="/lib/bootstrap/dist/js/bootstrap.js"></script> <script src="/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo"></script> <script src="/lib/jquery-validation/dist/jquery.validate.js"></script> <script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script><!-- Visual Studio Browser Link --><script type="application/json" id="__browserLink_initializationData"> {"requestId":"db2020dde36447d49b6a626dad3c3c43","requestMappingFromServer":false}</script><script type="text/javascript" src="http://localhost:53061/6ddbe519e8204b1d8cafa73b53ac5a72/browserLink" async="async"></script><!-- End Browser Link --></body></html>I'm submitting the CheckBoxList values using a Submit Button.What I have tried:I have tried setting breakpoints at various areas in my Edit Post and the values seem to be okay to me. But after I update the values they are incorrect. 解决方案 The view which uses CheckBoxListItems.chtml does not seem to included, most likely this is used in a loop for public List<checkboxlistitem> Devices { get; set; }. Also most of the code is not useful to the question.From this:"The problem that I'm having is, If I initially added DevId values (1, 3, 4 and 7) for CustId 1006 and then decide to remove just DevId value 1 it actually removes DevId values (3, 4 and 7) and leaves DevId value 1"This link may help: Model Binding To A List - You’ve Been Haacked[^] As per the link, your array must look something like this (copied from the link):<input type="text" name="[0].ID" value="1" /> --added<input type="text" name="[0].Title" value="Curious George" /><input type="text" name="[0].Author" value="H.A. Rey" /><input type="text" name="[0].DatePublished" value="2/23/1973" /><input type="text" name="[1].ID" value="3" /> --added<input type="text" name="[1].Title" value="Code Complete" /><input type="text" name="[1].Author" value="Steve McConnell" /><input type="text" name="[1].DatePublished" value="6/9/2004" />So most likely your data is being sent with only the 1st row:row[1]row[3] --brokenrow[4]row[7] --brokenAnd the reason for this (copied from link)Note that the index must be an unbroken sequence of integers starting at 0 and increasing by 1 for each element. 这篇关于Asp.net核心MVC编辑数据库中的checkboxlist值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!