Reputation: 2842
I have the following select list
public SelectList StaffList { get; set; }
I am assigning it the following,
inspectorCorrespondences.StaffList = new SelectList(userDetails, "Id", "FullName");
but I want to add in another SelectList item
var systemGeneratedUser = new SelectListItem() { Value = "-1", Text = "System Generated" };
how do I do that?
Upvotes: 2
Views: 8071
Reputation: 218877
According to the documentation, it looks like you need to initialize the SelectList
with the values instead of adding them. Passing an enumerable of SelectListItem
to the constructor appears to be the expected way.
It looks like you're already doing that in the sense that userDetails
is already an enumeration? If so, what type of enumeration is it? You may need to add a line or two of code to transform it to an enumeration of SelectListItem
objects, add yours to that, and then use that to initialize the SelectList
. Maybe something like this:
var listItems = userDetails.Select(u => new SelectListItem { Value = u.Id, Text = u.FullName }).ToList();
listItems.Add(new SelectListItem() { Value = "-1", Text = "System Generated" });
// or perhaps .Insert() at position 0 instead?
inspectorCorrespondences.StaffList = new SelectList(listItems, "Value", "Text");
Upvotes: 2
Reputation: 106
This isn't necessarily the most elegant solution, but you'll need to cast the SelectList's items to a list of SelectListItems if you want to add another SelectListItem.
var myItems = new List<SelectListItem>();
myItems.Add(new SelectListItem() { Text = "AA", Value = "11" } );
var mySelectList = new SelectList(myItems);
((List<SelectListItem>)mySelectList.Items).Add(new SelectListItem() { Text = "BB", Value = "22" });
Upvotes: 3