Cathal O 'Donnell Cathal O 'Donnell - 13 days ago 8
ASP.NET (C#) Question

Html.DropdownList with selected value

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?


You should use view models and forget about ViewBag Think of it as if it didn't exist. You will see how easier things will become. So define a view model:

public class MyViewModel
    public int SelectedCategoryId { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; } 

and then populate this view model from the controller:

public ActionResult NewsEdit(int ID, dms_New dsn)
    var dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();
    var categories = (from b in dc.dms_NewsCategories select b).ToList();

    var model = new MyViewModel
        SelectedCategoryId = dsn.NewsCategoriesID,
        Categories = categories.Select(x => new SelectListItem
            Value = x.NewsCategoriesID.ToString(),
            Text = x.NewsCategoriesName
    return View(model);

and finally in your view use the strongly typed DropDownListFor helper:

@model MyViewModel

    x => x.SelectedCategoryId,