Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

ASP.NET Core MVC Edit CheckBoxList values in Database

$
0
0

I'm having trouble understanding how to update the CheckBoxList values to the CustomerDevice table in my Database on the [HttpPost] Edit Action Method CustomerDeviceController.

My 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.

When I try to update the CheckBoxList values now I get the following error message below. I was told that I would need to loop through and delete the DevId values before I could update them. This is the part I'm having trouble understanding.

Error Message when updating CheckBoxList

An exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code

Additional information: The instance of entity type 'CustomerDevice' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.

Models

    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 class Device
    {
        public int DevId { get; set; }
        public string DevType { 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; }
    }

ViewModels

    public class CustomerDeviceFormViewModel
    {
        public int CustId { get; set; }
        public string CustDisplayName { get; set; }
        public List<CheckBoxListItem> Devices { get; set; }
    }

CustomerDeviceController

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.SingleOrDefault(c => c.CustId == vmEdit.CustId);

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

                IEnumerable<int> selectedDevices = vmEdit.Devices.Where(x => x.IsChecked).Select(x => x.ID);
                // Remove existing devices for the customer
                // Note following is for EF6
                db.CustomerDevices.RemoveRange(db.CustomerDevices.Where(x => x.CustId == vmEdit.CustId));


                // Add new selections
                foreach (int deviceId in selectedDevices)
                {
                    CustomerDevice customerDevice = new CustomerDevice
                    {
                        CustId = vmEdit.CustId,
                        DevId = deviceId
                    };
                    db.Add(customerDevice);
                }
                // Save and redirect
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(vmEdit);
        }

Edit View

<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>

Shared/EditorTemplates/CheckBoxListItem.chtml

<div class="checkbox"><label>
        @Html.HiddenFor(x => x.ID)
        @Html.CheckBoxFor(x => x.IsChecked)
        @Html.LabelFor(x => x.IsChecked, Model.Display)</label><br /></div>

 


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>