Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 871
Grace Avatar asked Feb 07 '23 10:02

Grace


1 Answers

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.

like image 150
Rafael A. M. S. Avatar answered Feb 12 '23 10:02

Rafael A. M. S.