Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create DropDownListFor using strings from a List<string>

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,

like image 885
Ben Avatar asked Oct 24 '25 05:10

Ben


1 Answers

I would recommend using the model directly in the view, instead of the ViewBag. Update your action to include a model reference:

public ActionResult ManageUserAccounts()
{
    var model = new ManageUserAccountsViewModel();
    model.UserList = oUsers.getUsersFullNames();
    return View(model);
}

Your model should be updated to include a selected User property:

public class ManageUserAccountsViewModel
{
    public string User { get; set; }

    [Display(Name = "Users")]
    public List<string> UserList { get; set; }
}

Your view should be binding to the model:

@model ManageUserAccountsViewModel

@Html.DropDownListFor(m => m.User, new SelectList(Model.UserList), "Select User")
like image 83
Travis Schettler Avatar answered Oct 26 '25 21:10

Travis Schettler