populating a DropDownlist in ASP.NET MVC

14,514

There is an error in the cast.

To fix you can do this:

var a = datacontext.services.Select(arg => new { ServiceID = arg.ServiceID }).ToList();
ViewData["ServiceID"] = new SelectList(a, "ServiceID", "ServiceID");

or this:

var a = datacontext.services.Select(arg => arg.ServiceID).ToList();
ViewData["ServiceID"] = new SelectList(a);

In your code a is the list of integers. It cannot be cast into the list of SelectListItem.

Side note: myList variable is not used in your code.

Share:
14,514
nishanth yeddula
Author by

nishanth yeddula

Updated on June 30, 2022

Comments

  • nishanth yeddula
    nishanth yeddula almost 2 years

    I'm learning ASP.NET MVC. I had a small problem when dealing with dropdownlist.

    This is what I did in controller

    List<Int32> myList = new List<Int32>();
    var a = (from m in datacontext.services
                     select m.ServiceID);
    myList = a.ToList();
    ViewData["ServiceID"] = new SelectList((IEnumerable<SelectListItem>)
                                    a.ToList(), "ServiceID", "ServiceID");
    

    In the view

     @Html.DropDownListFor(model => model.ServiceID, ViewData["ServiceID"] as SelectList)
    

    This results in an error

    Unable to cast object of type 'System.Collections.Generic.List1[System.Int32]' to type 'System.Collections.Generic.IEnumerable1[System.Web.Mvc.SelectListItem]'."

    How can this be resolved?

    What's the best way to deal with populating dropdownlist with a query?