I feel this should be simple but haven't found a guide on here that explains the use of dropdownlistfor in MVC.
I have a simple List of Names in a method in a class Users:
public List<string> getUsersFullNames()
{
return (from da in db.Dat_Account
join ra in db.Ref_Account on da.AccountID equals ra.AccountID
select ra.FirstName + " " + ra.Surname).ToList();
}
I want to display each of these names in a dropdownlist so that a name can be selected.
I tried to get this working but have had no success.
My controller:
[Authorize]
public ActionResult ManageUserAccounts()
{
ViewBag.UserList = oUsers.getUsersFullNames();
return View();
}
My Model:
public class ManageUserAccountsViewModel
{
[Display(Name = "Users")]
public List<SelectListItem> UserList { get; set; }
}
My View:
Html.DropDownListFor(model => model.UserList, new SelectList(oUsers.getUsersFullNames(), "Select User"));
I'm quite new to asp.net MVC as I have always used webforms in the past. Has anyone any idea if this is possible or a way to display this?
Thanks,
<select>toList<SelectListItem>. Your model needs a simple property to bind to (the value of the selected option), e.g.public string SelectedUser { get; set; }public List<string> UserList { get; set; }bepublic IEnumerable<SelectListItem> UserList { get; set; }and you use@Html.DropDownListFor(m => m.User, Model.UserList, "Select User")and the[Display]attribute needs to be onUser, notUserList