Grace Grace - 2 months ago 11
C# Question

Add Where condition to dropdown select list

I have a simple checkbox which is populated by my viewbag like this:

ViewBag.stuId_FK = new SelectList(db.CLS_Students, "stuId", "student");

This works fine.
What I am however trying to accomplish is, filter the conditions on by enforcing a where clause(example where my field "position" is 1).

I have this code but, I dont think this is accurate.

ViewBag.stuId_FK = new SelectList(db.CLS_Students, "stuId", "student").Where(o=>o.positionID==1);

Any help would be appreciated.Thank you


Try filtering the collection before instantiating a SelectList.

Like this:

ViewBag.stuId_FK = new SelectList(db.CLS_Students.Where(o=>o.positionID==1), "stuId", "student");

Doing this, you are filtering the data on your model instead of mapping the entire table on the memmory and then filtering.