C# ASP.NET MVC编辑数据库中的复选框列表值

C# ASP.NET MVC编辑数据库中的复选框列表值,c#,asp.net-core-mvc,C#,Asp.net Core Mvc,我很难理解如何根据CustId值从数据库中的CustomerDevice表中检索和编辑DevId值到复选框列表 CustomerDeviceController的“我的索引”操作方法显示“我的客户”表中的客户列表。我有一个标记为“Edit”的ActionLink,它将CustId值传递给CustomerDeviceController[HttpGet]Edit(int?id)操作方法,该方法当前显示设备表中的所有CheckBoxListItem值。但是,CheckBoxList不会将数据库中Cu

我很难理解如何根据CustId值从数据库中的CustomerDevice表中检索和编辑DevId值到复选框列表

CustomerDeviceController的“我的索引”操作方法显示“我的客户”表中的客户列表。我有一个标记为“Edit”的ActionLink,它将CustId值传递给CustomerDeviceController[HttpGet]Edit(int?id)操作方法,该方法当前显示设备表中的所有CheckBoxListItem值。但是,CheckBoxList不会将数据库中CustomerDevice表中选中的Device值显示到与CustId相关的CheckBoxList中,而是显示每个CheckBoxList值的检查结果

我很难理解和弄清楚的一点是,如何根据CustId将数据库中CustomerDevice表中选定的Device值显示到CheckBoxList,然后编辑/更新[HttpPost]上修改的CheckBoxListItems如果需要,请将操作方法编辑回数据库中的my CustomerDevice表

请看下面的代码,我到目前为止已经

型号

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 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; }
}
public class CustomerDeviceFormViewModel
{
    public int CustId { get; set; }
    public string CustDisplayName { get; set; }
    public List<CheckBoxListItem> Devices { get; set; }
}
视图模型

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 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; }
}
public class CustomerDeviceFormViewModel
{
    public int CustId { get; set; }
    public string CustDisplayName { get; set; }
    public List<CheckBoxListItem> Devices { get; set; }
}
公共类CustomerDeviceFormViewModel
{
public int CustId{get;set;}
公共字符串CustDisplayName{get;set;}
公共列表设备{get;set;}
}
客户设备控制器

public ActionResult Edit(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 = deviceList.Where(x => x.DevId == device.DevId).Any()
        });
    }
    customervm.Devices = checkBoxListItems;
    return View(customervm);
}

        [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();
            }

            foreach (var deviceId in vmEdit.Devices.Where(x => x.IsChecked).Select(x => x.ID))
            {
                var customerDevices = new CustomerDevice
                {
                    CustId = vmEdit.CustId,
                    DevId = deviceId
                };

                db.Entry(customerDevices).State = EntityState.Modified;
            }

            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(vmEdit);
    }
public ActionResult编辑(int?id)
{
if(id==null)
{
返回NotFound();
}
var customervm=new CustomerDeviceFormViewModel();
Customer=db.Customers.SingleOrDefault(c=>c.CustId==id);
如果(客户==null)
{
返回NotFound();
}
customervm.CustId=customer.CustId;
customervm.CustDisplayName=customer.CustDisplayName;
//检索CheckBoxList的设备列表
var deviceList=db.Devices.ToList();
var checkBoxListItems=新列表();
foreach(deviceList中的var设备)
{
添加(新的CheckBoxListItem()
{
ID=device.DevId,
Display=device.DevType,
IsChecked=deviceList.Where(x=>x.DevId==device.DevId).Any()
});
}
customervm.Devices=复选框列表项;
返回视图(customervm);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共操作结果编辑(CustomerDeviceFormViewModel vmEdit)
{
if(ModelState.IsValid)
{
Customer=db.Customers.SingleOrDefault(c=>c.CustId==vmEdit.CustId);
如果(客户==null)
{
返回NotFound();
}
foreach(vmEdit.Devices.Where(x=>x.IsChecked)中的var deviceId。选择(x=>x.ID))
{
var customerDevices=新的CustomerDevice
{
CustId=vmEdit.CustId,
设备ID=设备ID
};
db.Entry(customerDevices).State=EntityState.Modified;
}
db.SaveChanges();
返回操作(“索引”);
}
返回视图(vmEdit);
}
编辑.chtml

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

请选择要分配给@Html.DisplayFor(c=>c.CustDisplayName)的设备
@EditorFor(x=>x.Devices)
@Html.HiddenFor(c=>c.CustId)
提交
共享/EditorTemplate/CheckBoxListItem.chtml

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

@Html.HiddenFor(x=>x.ID)
@Html.CheckBoxFor(x=>x.IsChecked)
@LabelFor(x=>x.IsChecked,Model.Display)


以下是我使用过的Razor代码片段:

   foreach (SelectListItem p in Model.PositionList)
    {
    @Html.Raw(p.Text + "<input type=checkbox name=\"PositionIDs\" id=\"PositionIDs\" value=" + @p.Value + (Model.Positions != null && Model.Positions.Any(pos => pos.ScoreCardId == Convert.ToInt32(p.Value)) ? " checked />" : " />"));
    }
foreach(在Model.PositionList中选择ListItem p)
{
@Html.Raw(p.Text+“”:“/>”);
}

设置
IsChecked
值的代码将始终返回
true
(您的循环基本上是说,如果集合包含我(当然包含我),然后将其设置为true)

您需要通过从
CustomerDevice
表中读取值来获取每个
客户的选定值

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);
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)
})托利斯先生()
};
返回视图(模型);

您可能想看看MvcCheckBoxList NuGet包:


这使得在MVC中使用复选框列表做一些功能强大的事情变得更加容易,并且可能是解决复选框问题的更好方法。

我认为我的问题可能在CustomerDeviceController中,而不是在视图中。当我复制/粘贴您的解决方案时,它会说我缺少了
。这行代码是不是
IEnumerable selectedDevices=db.CustomerDevices.Where(x=>x.CustId==id).Select(x=>x.DevId)仅为变量selectedDevices创建一个int数组?请参见编辑(最后第二行缺失
)。是的,
selectedDevices
是一个只包含
DevId
值的集合谢谢!我收到另一条错误消息,但找到了相应的修复方法。I修改了
var deviceList=db.Devices
to
var deviceList=db.Devices.ToList()它仍然不工作吗?(我可以为你制作一个简单的小提琴,如果你仍然有问题的话,展示它是如何工作的)它现在工作得很好。现在只需要找出[HttpPost]编辑操作方法来更新DevId值i