I trying to create a drop down list and bind it to the values fetched from database. How can I do this. I have done following till now. I want the value of the items of the dropdown ie c.ID in following code to be bind with the Currency_ID of the CountryVM.

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

        }

//Controller

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

//In View I am trying to access my DropDown as follows :

     @Html.DropDownListFor(model => model.Currency_ID,"curr_symbol" )// how to write this.
有帮助吗?

解决方案

Do like this in view:

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

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

and in action:

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

or:

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

Update:

As you told in discussion that it is throwing exception on form post so what you need is to fill the List again and put it in ViewBag in post action as from ViewBag it is removed.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top