Reputation: 1729
I have a dropdown with checkboxes in it. Lets say I've the following data displayed in the dropdown:
<select multiple="multiple" name="Products" id="Products">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
Then I checked record no 4, 2, 3 and submit the page. In the controller I change the int[] arrIDs
into List<int> listIDs
to collect the Products from the database.
List<Product> products = db.Product
.Where(d => listIDs.Contains(d.ProductID))
.ToList();
But I've got the products
is sorted in the following sequence 2, 3, 4. I want to keep the sequence based on the records that I've selected in the page 4, 2, 3. How to solve it?
Upvotes: 1
Views: 441
Reputation: 42354
You need to do a GroupJoin
:
List<Product> products = listIDs
.GroupJoin(
db.Product,
x => x,
y => y.ProductID,
(x, ys) => ys.First())
.ToList();
This performs the equivalent of a "left outer join", which maintains the values of listIDs
in their original order, then matches each listID
with the corresponding product in the table.
Note: this code assumes there is always a single matching ProductID
in the database.
Upvotes: 0
Reputation: 1238
The multiple select box does not preserve the order of clicks.
You'll need to use Javascript to watch the clicks, and record the order into a hidden field, which will be submitted with the form. Or give up on the multiple select box, and use a component like this one. (That's not a .NET component, but I suspect that similar ones exist.)
Upvotes: 1
Reputation: 460108
You can use List.IndexOf
to get the index for the order:
List<Product> products = db.Product
.Where(d => listIDs.Contains(d.ProductID))
.AsEnumerable()
.OrderBy(d => listIDs.IndexOf(d.ProductID))
.ToList();
Upvotes: 3