Grace
Grace

Reputation: 89

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

Upvotes: 4

Views: 2648

Answers (1)

Rafael A. M. S.
Rafael A. M. S.

Reputation: 637

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 memory and then filtering.

Upvotes: 8

Related Questions