Mr A
Mr A

Reputation: 6768

how to get checkbox list to be checked depending on the db values in mvc

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>

Upvotes: 0

Views: 2855

Answers (1)

amurra
amurra

Reputation: 15401

To get a checkbox to be checked you need to set the checked attribute on the input element

<input type="checkbox" name="Name" value="<%=item.Value %>" checked="checked" />

EDIT:

Assuming you always want 1, 2, or 3 checked you can do this:

  <% var valuesToCheck = new List<int>() { 1, 2, 3 };

    foreach (var item in (SelectList)ViewData["products"]) { 
       string checkedString = valuesToCheck.Contains(item.productID) ? "checked=/"checked/" : string.empty;
    %>
     <input type="checkbox" name="Name" value="<%=item.Value %>" <%=checkedString%> />
     <label for="<%=item.Value%>"><%=item.Text%></label>
     <br />

<% } %>  

I would probably pass over the values you want checked as part of your viewmodel or if you aren't using one in ViewData so as to not define a list in the view.

Upvotes: 1

Related Questions