Consider we have this three tables
TblProducts
+----+----------+-------+
| Id | Title | Price |
+----+----------+-------+
| 1 | product1 | 1000 |
| 2 | product2 | 1000 |
| 3 | product3 | 1000 |
| 4 | product4 | 1000 |
+----+----------+-------+
TblOrders
+----+----------+-----------+
| Id | UserName | OrderDate |
+----+----------+-----------+
| 1 | user1 | 6/22/2018 |
+----+----------+-----------+
TblOrderItems
+----+---------+-----------+
| Id | OrderId | ProductId |
+----+---------+-----------+
| 1 | 1 | 2 |
| 1 | 1 | 4 |
| 1 | 1 | 5 |
+----+---------+-----------+
I want to show a list of products using checkboxes, so the user can select products
and then Insert order info in TblOrders and selected products Id's in TblOrderItems at the same time.
In the controller, I fetch products list and put it in ViewBag
public ActionResult Create()
{
ViewBag.ProductList = db.TblProducts.ToList();
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,UserName,OrderDate")] TblOrder tblOrder,???????????????)
{
if (ModelState.IsValid)
{
db.TblOrders.Add(tblOrder);
foreach (var item in ???????????????)
{
db.TblOrderItems.Add(
new TblOrderItem()
{
OrderID=tblOrder.Id,
ProductID= item.Id
}
);
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tblOrder);
}
and in view I get ViewBag like below:
@model test.Models.TblOrder
@using test.Models
@{
ViewBag.Title = "Create";
List<TblProduct> productLists = ViewBag.ProductList;
}
But I don't know how to write part below
@foreach (var item in productLists)
{
????????????????????????????????????????
@*<input name="" type="checkbox" />
<label>@item.Title</label>*@
}
how can bind checkboxes with products and how can access select products Ids in the controller?
please consider we have to do this using ViewBag not ViewModel, and inputs with type checkboxes not MVC checkboxlist helper.
thanks