I'm trying to generate a DropDownList for each record in a table in a View. I have trouble setting the selected value for the dropdownlist.
In the controller each user's access level list in the model is populated by calling a method in the Repository. I can't seem to get this method quite right. I can change the selected value on item, and accessLevels has correct value selected. But in the view this is not the selected value. How can I set the selected value of a selectlist?
I've tried this:
Repository:
public IEnumerable<SelectListItem> GetSelectListAccessLevelsWithSelectedItem(string selectedAccessLevelID)
{
IEnumerable<SelectListItem> accessLevelsFromDB = DB.AccessLevels
.Select(x => new SelectListItem
{
Value = x.AccessLevelID.ToString(),
Text = x.Name
});
SelectListItem item = null;
foreach (SelectListItem a in accessLevelsFromDB)
{
if (a.Value == selectedAccessLevelID)
{
item = a;
a.Selected = true;
}
}
var accessLevels = new SelectList(accessLevelsFromDB, item.Value);
return accessLevels;
}
And also tried returning accessLevelsFromDB:
return accessLevelsFromDB;
View:
@Html.DropDownList("Accesslevels", user.AccessLevelsWithSelectedItem, new { @class = "form-control", @name = "accessLevels"})
Have I used, SelectList Constructor (IEnumerable, Object), correctly? Or what else am I missing? I have tried to google but still don't understand what I'm doing wrong. I Looked at this question SelectList Selected Value Issue - Stack Overflow but that doesn't seem to work.
Update:
this is the model:
public class EditCustomerViewModel
{
public Customer Customer { get; set; }
public int CustomerID { get; set; }
public List<User> Users { get; set; }
public List<UserToView> UsersToView { get; set; }
public IEnumerable<SelectListItem> AccessLevelListForSelectedUser { get; set; }
}
Update 2:
I've got it working now and have updated my model and repository.
Model:
public class EditCustomerViewModel
{
public Customer Customer { get; set; }
public int CustomerID { get; set; }
public List<UserToView> UsersToView { get; set; }
}
Repository:
public IEnumerable<SelectListItem> GetSelectListAccessLevelsWithSelectedItem(string selectedAccessLevelID)
{
IEnumerable<SelectListItem> accessLevelsFromDB = DB.AccessLevels
.Select(x => new SelectListItem
{
Value = x.AccessLevelID.ToString(),
Text = x.Name,
Selected = x.AccessLevelID.ToString() == selectedAccessLevelID
});
return accessLevelsFromDB;
}