I am trying to build a simple drop down list for my MVC application. I have a method that gets me a List, which is has properties with account name, id, deleted etc etc... and holds different bank accounts.
In my controller, I am calling this, then using Linq, trying to build a SelectItemList... like this:
public ActionResult AccountTransaction(AccountTransactionView model)
{
List<AccountDto> accounts = Services.AccountServices.GetAccounts(false);
AccountTransactionView v = new AccountTransactionView();
v.Accounts = (from a i开发者_运维问答n accounts
select new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString(),
Selected = false
});
return View();
}
However, it's failing, saying that I can't convert IEnumerable SelectListItem to SelectList.
My AccountTransactionView is defined like this:
public class AccountTransactionView
{
public SelectList Accounts { get; set; }
public int SelectedAccountId { get; set; }
}
A SelectList is a wrapper that contains the SelectListItems. You can create a SelectList by passing in the IEnumerable and optionally the selected item.
Edit: Sorry, I wasnt' really clear. What I mean is that you should use the SelectList with the IEnumerable in the construstor instead of the IEnumerable by itself:
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();
}
精彩评论