0

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 in 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; }

}
Craig
  • 18,074
  • 38
  • 147
  • 248
  • possible duplicate of [Asp.Net MVC with Drop Down List, and SelectListItem Assistance](http://stackoverflow.com/questions/4833652/asp-net-mvc-with-drop-down-list-and-selectlistitem-assistance) – Darin Dimitrov Jan 29 '11 at 08:28

1 Answers1

1

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();
}
John Landheer
  • 3,999
  • 4
  • 29
  • 53