数据库

时间:2016-10-31 17:00:40

标签: c# asp.net-core-mvc

我无法理解如何根据CustId值从我的数据库中的CustomerDevice表检索和编辑DevId值到CheckBoxList。

CustomerDeviceController的我的索引操作方法显示来自Customers表的Customers列表。我有一个标记为“编辑”的ActionLink,它将CustId值传递给CustomerDeviceController [HttpGet] Edit(int?id)Action方法,该方法当前显示Devices表中的所有CheckBoxListItem值。但是,CheckBoxList不会将数据库中CustomerDevice表中已检查的DevId值显示到与CustId相关的CheckBoxList,而是显示每个CheckBoxList值的检查。

我无法理解和弄清楚的部分是,我如何在数据库中将CustomerDevice表中的选定DevId值显示到基于CustId的CheckBoxList,然后在[[更改]上修改/更新修改后的CheckBoxListItems HttpPost]如果需要,可以将Action Action方法返回到我的数据库中的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; }
}

的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)
{
    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);
    }

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

共享/ EditorTemplate / 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 />

3 个答案:

答案 0 :(得分:1)

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

您需要通过阅读Customer

中的值来获取每个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);

答案 1 :(得分:0)

这是我使用过的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 />" : " />"));
    }

答案 2 :(得分:-1)

您可能想要查看MvcCheckBoxList NuGet包:

https://www.nuget.org/packages/MvcCheckBoxList/

这使得在MVC中使用CheckBoxList做一些功能更加强大 - 并且可能是修复CheckBox问题的更好方法。

相关问题