I have a drop down list that is being populated via a ViewBag variable, I am wondering how I can set the selected index of this list using the id value.
This is where I create the ViewBag variable, note the id, this is what I want to use to set the default selected item in the list:
var events = db.Events.Select(e => new
{
id = e.EventID,
Name = e.EventTitle
}).OrderBy(e => e.Name).ToList();
ViewBag.EventsList = new MultiSelectList(events, "id", "Name");
This is the dropdown in the View:
@Html.DropDownList("id", (MultiSelectList)ViewBag.EventsList, new { @class = "form-control", id = "lstTopFeaturedEvent" })
Is there anyway I could set the default select value using the id property set in the controller?
idin the GET method before you pass the model to the view (and you can simply useViewBag.EventsList = new SelectList(db.Events, "EventID", "EventTitle");)