动态绑定MVC 4中的下拉列表

时间:2014-04-18 11:49:57

标签: asp.net-mvc-4 drop-down-menu entity

我尝试创建一个下拉列表并将其绑定到从数据库中获取的值。  我怎样才能做到这一点。到目前为止我已经完成了。我想要下拉列表项的值,即以下代码中的c.ID与CountryVM的Currency_ID绑定。

 public CountryVM()
    {      
            [DisplayName("Country ID")]
            [Required]
            public string ID { get; set; }

            [Required]
            [DisplayName("Description")]
            public string Description { get; set; }


            [DisplayName("Currency Id")]
            public Nullable<int> Currency_ID { get; set; }

        }

//控制器

   DAL library = new DAL();
   var items = library.GetAllCurrency(Library.Filter.CURRENCY_SYMBOL);
   IEnumerable<SelectListItem> list = items.Select(c => new SelectListItem { Text = c.CURRENCY_SYMBOL, Value = c.ID.ToString() });

    ViewBag.curr_symbol = list;
    return View();

//在View中我试图按如下方式访问我的DropDown:

     @Html.DropDownListFor(model => model.Currency_ID,"curr_symbol" )// how to write this.

1 个答案:

答案 0 :(得分:0)

在视图中这样做:

@
{
SelectList CurrencyList = (SelectList)ViewBag.curr_symbol;
}

@Html.DropDownListFor(model => model.Currency_ID,CurrencyList)

并在行动中:

IEnumerable<SelectListItem> list = items.Select(c => new SelectListItem { Text = c.CURRENCY_SYMBOL, Value = c.ID.ToString() }).ToList();

或:

var list = (from c in items
           select new SelectListItem {Text = c.CURRENCY_SYMBOL, 
                                      Value = c.ID.ToString() }).ToList();

<强>更新

正如您在讨论中所说的那样,它会在表单帖子上抛出异常,所以您需要的是再次填充列表并将其放在ViewBag的帖子操作中,从ViewBag移除它。< / p>