2011-08-04 70 views
0

我在編輯產品頁面有一個checboxlist,我希望根據db值檢查複選框列表爲 。如何獲取複選框列表根據mvc中的db值進行檢查

例如,我將數據保存在db中作爲1,2,3 因此,應該檢查值爲1,值2,值3的複選框列表。

下面是代碼: 控制器:

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

查看:

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

編輯:

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

回答

1

爲了得到一個複選框被選中需要設置的檢查屬性輸入元素

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

編輯:

假設你總是希望1,2,或3中選中了,你可以這樣做:

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

<% } %> 

我很可能會通過在要檢查作爲你的視圖模型的一部分或值如果您沒有在ViewData中使用它,以便不在視圖中定義列表。

+0

我知道,但我不想檢查所有的複選框,只是有值匹配db值的複選框 –

+0

@Mr A - 哪個對象/屬性包含數據庫值,哪些包含所有其他值? – amurra

+0

item.productID包含像1,2,3這樣的值因此我想檢查複選框,它的值是1 nd 2 nd 3 –

相關問題