Nathan McKaskle Nathan McKaskle -4 years ago 255
C# Question

Show Only One Specific Value In DropDown

I'm trying to only show one of the statuses in the dropdown in this particular view. In the controller for the get create method I have this:

ViewBag.StatusId = new SelectList(db.statuses, "StatusId", "StatusName");

I know the fourth option for select list can specify a specific selected item but what if I only want to show one of the items this time?

Here's the model:

public class Status
public int StatusId { get; set; }

[Required(ErrorMessage = "Status is required.")]
[Display(Name = "Status")]
public string StatusName { get; set; }

Answer Source

you can use linq to filter that specific value by using where

ViewBag.StatusId = new SelectList(db.statuses.Where(x=>x.StatusName == "Pending Approval"), "StatusId", "StatusName");

this will display only value which matches the condition. In this case you cannot use .Single because new select expects list

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download