Question

ViewBag.WList = new SelectList(_bdb.BMW.OrderBy(o => o.NAME).AsEnumerable(), "ID", "NAME");

This is how I've setup my selectlist in the controller with below the view code.

@Html.DropDownList("WOptions", (SelectList)ViewBag.WList, "Select an option", new { style = "width:250px;" })

I have a table in my database which I can't add new records too and which I need to reference as my main option list, additionally I need to add 2 new records to reference exceptions.

Basically on my create form I have my option list and a type list since 1 of the options isn't suitable so 2 new choices have been added as a different dropdown in the form of the type list.

It's mostly not a problem to record this or display it but I have a filter on my kendo list based on the code above.

I'm wondering what the best method of adding in 2 options to the ward list would be if I can do it with my existing code or need to use a different method?

Additionally I've tried,

SelectList options = new SelectList(_bdb.BMW.OrderBy(o => o.NAME).AsEnumerable(), "ID", "NAME");
        options.ToList().Insert(11, (new SelectListItem { Text = "Example1", Value = "11" }));
        options.ToList().Insert(22, (new SelectListItem { Text = "Example2", Value = "22" }));
ViewBag.WList = options;

While this does still display the original selectlist it doesn't display the new items and this has so far been the only variant which didn't cause errors.

Any ideas or suggestions would be much appreciated.

Was it helpful?

Solution

The Linq Extension .ToList() returns a new instance of List. So options.ToList() does not reference to the internal list and that is why the later two items are not inserted to the internal list. To go around,

var bmws = _bdb.BMW.OrderBy(o => o.NAME).Select(x => new { ID = x.ID, NAME = x.NAME }).ToList();
bmws.Insert(11, (new { ID = "11", NAME = "Example1" }));
bmws.Insert(22, (new { ID = "22", NAME = "Example2" }));
var options = new SelectList(bmws.AsEnumerable(), "ID", "NAME");

I have not tested the code, but this should do the trick. Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top