使用 List<string> 中的字符串创建 DropDownListFor

Create DropDownListFor using strings from a List<string>

我觉得这应该很简单,但在这里没有找到解释在 MVC 中使用 dropdownlistfor 的指南。

我在 class 用户的方法中有一个简单的名称列表:

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();
    }

我想在下拉列表中显示这些名称中的每一个,以便可以选择一个名称。

我试图让它工作但没有成功。

我的控制器:

[Authorize]
    public ActionResult ManageUserAccounts()
    {
            ViewBag.UserList = oUsers.getUsersFullNames();
            return View();
    }

我的模特:

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

我的观点:

Html.DropDownListFor(model => model.UserList, new SelectList(oUsers.getUsersFullNames(), "Select User"));

我对 asp.net MVC 很陌生,因为我过去一直使用网络表单。有谁知道这是否可行或显示它的方法?

谢谢,

我建议直接在视图中使用模型,而不是 ViewBag。更新您的操作以包含模型参考:

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

您的模型应更新为包含选定的用户 属性:

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

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

您的视图应该绑定到模型:

@model ManageUserAccountsViewModel

@Html.DropDownListFor(m => m.User, new SelectList(Model.UserList), "Select User")