I have 2 lists of different types –
List
List
The db tables are structured as follows
Product
-----------
ProductID - PK
Name
Description
Price
OwnerID - FK
...
SelectedProducts
---------------
SelectedProductID - PK
ProductID - FK
Active
So I have a page where the user is displayed a list of products, they can select some or all of the products. I am now trying to create an edit page which displays a full list of products, but checks the checkboxes for products already selected.
I have tried the following approaches, however both give me duplicates of some sort –
Approach 1
This approach gives me a list of products, and then duplicates the products because of the ones already selected.
<div style="margin-left: 10px; margin-top: 10px;">
<% foreach (var product in Model.Products) { %>
<% foreach (var p in Model.SelectedProducts)
{ %>
<% if (p.ProductID == product.ProductID)
{ %>
<div style="float: left; line-height: 18px; padding: 2px; margin: 2px; vertical-align: middle;
border: 1px solid grey; width: 282px;">
<input type="checkbox" name="PRODUCT_<%: product.Name %>" value="<%: ViewData["PRODUCT_" + product.ProductID] %>" checked="checked" style="vertical-align: middle; padding-left: 5px;" />
<%: Html.Truncate(product.Name, 35) %>
</div>
<% } %>
<% } %>
<div style="float: left; line-height: 18px; padding: 2px; margin: 2px; vertical-align: middle;
border: 1px solid grey; width: 282px;">
<input type="checkbox" name="PRODUCT_<%: product.Name %>" value="<%: ViewData["PRODUCT_" + product.ProductID] %>" style="vertical-align: middle; padding-left: 5px;" />
<%: Html.Truncate(product.Name, 35) %>
</div>
<% } %>
</div>
Approach 2
<div style="margin-left: 10px; margin-top: 10px;">
<% foreach (var product in Model.Products) { %>
<% foreach (var p in Model.SelectedProducts)
{ %>
<% if (p.ProductID == product.ProductID)
{ %>
<div style="float: left; line-height: 18px; padding: 2px; margin: 2px; vertical-align: middle;
border: 1px solid grey; width: 282px;">
<input type="checkbox" name="PRODUCT_<%: product.Name %>" value="<%: ViewData["PRODUCT_" + product.ProductID] %>" style="vertical-align: middle; padding-left: 5px;" />
<%: Html.Truncate(product.Name, 35) %>
</div>
<% } else { %>
<div style="float: left; line-height: 18px; padding: 2px; margin: 2px; vertical-align: middle; border: 1px solid grey; width: 282px;">
<input type="checkbox" name="PRODUCT_<%: product.Name %>" value="<%: ViewData["PRODUCT_" + product.ProductID] %>" checked="checked" style="vertical-align: middle; padding-left: 5px;" />
<%: Html.Truncate(product.Name, 35) %>
</div>
<% } %>
<% } %>
<% } %>
</div>
I know it’s just a silly logic error but I could do with a fresh pair of eyes!
If you remove the inner loop and instead just test each item in the outerloop against your selected products list, you should be good to go: