Asp.net mvc 构建DropDownList和Asp.NETMVC

Asp.net mvc 构建DropDownList和Asp.NETMVC,asp.net-mvc,drop-down-menu,Asp.net Mvc,Drop Down Menu,我正在尝试为我的MVC应用程序构建一个简单的下拉列表。我有一个方法,让我一个列表,这是有帐户名,id,删除等属性。。。持有不同的银行账户 在我的控制器中,我调用它,然后使用Linq,尝试构建SelectItemList。。。像这样: public ActionResult AccountTransaction(AccountTransactionView model) { List<AccountDto> accounts = Services

我正在尝试为我的MVC应用程序构建一个简单的下拉列表。我有一个方法,让我一个列表,这是有帐户名,id,删除等属性。。。持有不同的银行账户

在我的控制器中,我调用它,然后使用Linq,尝试构建SelectItemList。。。像这样:

        public ActionResult AccountTransaction(AccountTransactionView model)
    {
        List<AccountDto> accounts = Services.AccountServices.GetAccounts(false);

        AccountTransactionView v = new AccountTransactionView();
        v.Accounts = (from a in accounts
                      select new SelectListItem
                                 {
                                     Text = a.Description,
                                     Value = a.AccountId.ToString(),
                                     Selected = false
                                 });



        return View();
    }
    public class AccountTransactionView
{
    public SelectList Accounts { get; set; }
    public int SelectedAccountId { get; set; }

}

SelectList是包含SelectListItems的包装器。您可以通过传入IEnumerable和可选的选定项来创建SelectList

编辑: 对不起,我不是很清楚。我的意思是,您应该在构造函数中使用带有IEnumerable的SelectList,而不是IEnumerable本身:

    List<AccountDto> accounts = Services.AccountServices.GetAccounts(false);

    AccountTransactionView v = new AccountTransactionView();
    v.Accounts = new SelectList(
                       (from a in accounts
                        select new SelectListItem
                                   {
                                       Text = a.Description,
                                       Value = a.AccountId.ToString(),
                                       Selected = false
                                   }
                       )
                       );

    return View();
}
List accounts=Services.AccountServices.GetAccounts(false);
AccountTransactionView v=新的AccountTransactionView();
v、 Accounts=new SelectList(
(来自账户中的a)
选择新的SelectListItem
{
Text=a.说明,
Value=a.AccountId.ToString(),
所选=错误
}
)
);
返回视图();
}

我以为我在这么做。我在上面的代码中做错了什么?我已经修改了我的数据类以使用public IEnumerable Accounts{get;set;},这允许代码进行编译,但这是正确的吗?请将SelectList保留在数据类中,并查看我编辑过的其余答案。可能重复的