ASP.NET MVC将CheckBoxList值插入数据库

时间:2016-10-26 19:44:28

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

我无法理解如何将CheckBoxList中的CustId和选定的DevId值添加到数据库中的CustomerDevice表中。

CustomerDeviceController的我的索引操作方法显示来自Customers表的Customers列表。我有一个标有" Add Device(s)"的链接。将CustId值传递给CustomerDeviceController [HttpGet]创建操作方法,该方法显示我的CheckBoxListItem值来自Devices表,工作正常。

我理解和搞清楚的部分是如何将CheckBoxList中选定的DevId值和CustId值一起添加到[HttpPost]创建操作方法的CustomerDevice表中。

请参阅我目前的以下代码。

CheckBoxListItem模型

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

CustomerDevice Model

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

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

共享/ EditorTemplates / CheckBoxListItem.cshtml

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

CustomerDeviceController

public class CustomerDeviceController : Controller
{
    private CheckBoxAppContext db;

    public CustomerDeviceController(CheckBoxAppContext 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;

            // 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)
        {
            var customerDevices = new CustomerDevice();
            {
                customerDevices.CustId = vm.CustId;

                var deviceList = db.Devices.ToList();
                var checkBoxListItems = new List<CheckBoxListItem>();
                foreach (var deviceId in deviceList)
                {

                }
            }

            db.CustomerDevices.Add(customerDevices);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        else
        {
            return View(vm);
        }
    }
}

索引视图

<table class="table">
<tr>
    <th>Id</th>
    <th>Display Name</th>
    <th>Actions</th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CustId)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CustDisplayName)
        </td>
        <td>
            @Html.ActionLink("Add Device(s)", "Create", new { id = item.CustId })
        </td>
    </tr>
}

创建视图

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

1 个答案:

答案 0 :(得分:1)

假设您的CustomerDeviceCustomerDevice个实体之间M:N关系的联接表,我认为您的POST行动中需要这样的内容:

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

您可以创建连接表的实体并将其添加到上下文中。当您致电SaveChanges时,EF会将记录关联起来。

希望这有帮助!