Reputation: 604
I have a model that looks like this:
public partial class ProgramType
{
public int PgmId { get; set; }
public string PgmDescr { get; set; }
public string PgmDescrLong { get; set; }
public virtual ICollection<NewProgram> NewProgram { get; set; }
public virtual ICollection<NewForm> NewForm { get; set; }
}
Which is populated with this data:
+-------+----------+--------------+
| PgmId | PgmDescr | PgmDescrLong |
+-------+----------+--------------+
| 1 | CERT | Certificate |
+-------+----------+--------------+
| 2 | DEG | Degree |
+-------+----------+--------------+
| 3 | DIP | Diploma |
+-------+----------+--------------+
Using EF Core, I have scaffolded a Controller for the NewProgram model. The Create() action defines the Value/Text fields of a dropdown list which displays items from the ProgramType table:
ViewData["ProgramType"] = new SelectList(_context.ProgramType, "PgmId", "PgmDescrLong");
But I want to limit the dropdown list to particular values depending on which Controller I'm working on. I can get this to limit the dropdown list to display only "Certificate":
ViewData["ProgramType"] = new SelectList(_context.ProgramType, "PgmId", "PgmDescrLong").Where(x => x.Text.Contains("Certificate"));
But I want it to show both "Certificate" and "Diploma". This does not work:
ViewData["ProgramType"] = new SelectList(_context.ProgramType, "PgmId", "PgmDescrLong").Where(x => x.Text.Contains("Certificate", "Diploma"));
How can I accomplish this?
Upvotes: 1
Views: 1021
Reputation: 9171
Try this:
string[] strArray = new string[] { "Certificate", "Diploma" };
ViewData["ProgramType"] = new SelectList(db.Programs, "PgmId", "PgmDescrLong").Where(x => strArray.Any(y => y == x.Text));
What you do is that create an array of string that you want to show on your dropdownlist.
From there, we will use that array to create a query that is like a SQL IN
operator query just like this one:
Where(x => strArray.Any(y => y == x.Text));
Upvotes: 1