簡體   English   中英

建立DropDownList和Asp.Net MVC

[英]Building DropDownList and Asp.Net MVC

我正在嘗試為我的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();
    }

但是,這失敗了,說我無法將IEnumerable SelectListItem轉換為SelectList。

我的AccountTransactionView的定義如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM