I have got a checboxlist in edit products page, I want the checkbox list to be checked depending on the db values.
For instance I am saving the values in db as 1,2,3 Therfore the checkboxlist with the value 1 , value 2 , value 3 should be checked.
Below is the code: Controller:
public ActionResult Edit(int id)
{
ITrackdayRepository trackdayResp = new TrackdayRepository();
IQueryable<Object> getAllproducts = trackdayResp.GetProductsSelectlist();
ViewData["products"] = new SelectList(getAllproducts.ToList(), "productID", "Name");//all events for checkboxlist
IVoucherRepository voucherResp = new VoucherRepository();
Voucher voucher = voucherResp.GetVoucher(id);
return View(voucher);
}
//
// POST: /Admin/Voucher/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: update the selected checkbox nd do db insert
return RedirectToAction("Index");
}
catch
{
return View();
}
}
View:
<tr>
<td>
<label>Products</label>
</td>
<td>
<% foreach (var item in (SelectList)ViewData["products"]) { %>
<input type="checkbox" name="Name" value="<%=item.Value %>" />
<label for="<%=item.Value%>"><%=item.Text%></label>
<br />
<% } %>
</td>
</tr>
edited:
<td>
<% foreach (var item in (SelectList)ViewData["events"]) { %>
<%var test = ViewData["arrays"]; %>
<%string checkString = test.ToString().Contains(item.Value) ? "checked=\"checked\"":string.Empty; %>
<input type="checkbox" name="Name" value="<%=item.Value %>" checked="<%=checkString %>" />
<label for="<%=item.Value%>"><%=item.Text%></label>
<br />
<% } %>
</td>